• 0

Algorithm Help


Question

Alright, I already passed a basic Algorithms course in school, but a friend who's taking it needs help with an exercise. I can't for the life of me figure out a simple way to do this... it is being made using a flowchart-generator, not a real programming language, so I can't access any advanced functions. This is the scenario:

You have to chose the cheapest, most efficient way to get somewhere. Now, assume the following price lists:

  • 1 KM: $12
  • 2 KM: $21
  • 3 KM: $31
  • 4 KM: $40
  • 5 KM: $49
  • 6 KM: $58
  • 7 KM: $69
  • 8 KM: $79
  • 9 KM: $90
  • 10KM: $101

So for example, the cheapest way to get a 15 KM trip would be to pay for a 3 KM trip and two 6 KM ones. What would the algorithm for this be like? I'm having a hard time with it..

Thanks in advance!

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/
Share on other sites

16 answers to this question

Recommended Posts

  • 0

There seems to be no rule between KM and $ on your price list, so you need to sort them by km/price ratio and always use combinations made of the cheapest trips, reverting to higher priced one when adding a cheaper one would get you too far.

Maybe it's more complex than that, though. :unsure:

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590153416
Share on other sites

  • 0

Well, the above logic run good

But I guess this will also do!!!

Hope you would appreciate :)

Try this

Step 1.

Factor your distance to travel into prime factors

Step 2.

Suppose, u want to travel 15kms then after factorizing you will able to get it as product of 3*5

i.e 5 times three, no as from your table of KM's to Cost i c that rate even km's is slightly less than the that of odd ones.

So form even numbers of the factorzing number as much as possible

for 15km's it would be (3+3)+(3+3) + 3

which would result into your required least cost!!! :)

Hope it helps, plz feel free to comment

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590154482
Share on other sites

  • 0
Seems easy enough. Here's how:

1. Calculate the cost/km for each km/$ pair, and sort them

2. Take the lowest cost/km and subtract as many kms as you can, keeping track.

3. Take the next lowest and repeat as per step 2

(Y)

:no:

Sorry, but my algorithm doesn't work, at least not in the general case.

Consider the following:

10km - $10 = $1/km

1km - $5 = $5/km

8km - 9$ = $1.125/km

Now say you want to go 16km. According to the algorithm I gave, you would take 1 - 10km and 6 - 1km, which would add up to $40. Now, you could take 2 - 8km which would give you $18.

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590159638
Share on other sites

  • 0

If you don't need the most efficient algorithm... and want to save yourself a headache...

Start by computing a possible path. Any one. That will cost a certain amount. Save that amount as the cheapest known path.

Now go through all possible combinations. This might be prohibitingly expensive, but you can break out of any calculation as soon as it exceeds the cheapest known path, and avoid equivalent permutations (2x8kms + 3x1km == 3x1km + 2x8kms). When a cheaper path is found, update your cheapest known path variable.

When all possibilities have been examined, you have the cheapest path!

Of course, given a long list of prices, this might take a while. For 10 prices, for instance, the worst case scenario will require to evaluate 92 378 possibilities, and that's if you avoid equivalent permutations. For 20 prices, worst case scenario is 68 923 264 410 possibilities avoiding equivalent permutations.

If you don't bother avoiding equivalent permutations (consider order important), then worst case scenario is n^n. :p

EDIT: actually the number of possiblities is MUCH lower if you only consider those that make up the required number of kilometers.

Edited by Dr_Asik
Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590161040
Share on other sites

  • 0

Maybe a possible way to start would be to assign each of the pricings a variable.

Read in the trip length and run it through a loop that would break it down starting with 10 and down to 1.

Probably would if/else using modulus (remainder) to make sure you get integer values. (If that even makes sense?)

Then obviously once you have the pricing choices, calculate out the total price using the variables.

My brain is drained from finals, so I don't know if any of that makes sense. Maybe you'll get some sort of idea from it.

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590161208
Share on other sites

  • 0
:p

EDIT: actually the number of possiblities is MUCH lower if you only consider those that make up the required number of kilometers.

Or it could be much higher if the list of prices stayed like the one the OP listed but the distance you want to cover is much higher (i.e. 5000 km).

In that regard, you could use the lowest price per kilometer fare until you are within the distance of the longest trip available.

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590164696
Share on other sites

  • 0

well, i found a good one that might work,

here it's simply

before startl, naming:

km = KM trip

cost(int km) //a method that calculate the least cost combination of trips

{

if ( km <=0 ) invalid trip

else if ( 1 <= km < 9 )

use the mentioned prices. i.e. 1 km => $12, 8 Km => $79

else //(km >= 9)

(km/5) * cost(km/2) + cost(cost%2)

}

notice that the km/2 and km%2 are integers i.e 9/2 = 4 and 9%2 = 1

I know this is NOT an algorithm exactly and not an complete code, it is in between and it must be done "Recursively"

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590196144
Share on other sites

  • 0
This is the unbounded knapsack problem (see http://en.wikipedia.org/wiki/Knapsack_problem). The greedy algorithm won't necessarily give you the optimal solution. You should take a look at a dynamic programming solution.

OMG! this is exactly what I did :-) even though I didn't know about that !!!

We can define A(j,Y) recursively as follows:

A(0, Y) = 0 
A(j, 0) = 0 
A(j, Y) = A(j − 1, Y)  if wj &gt; Y 
A(j, Y) = max { A(j − 1, Y),  pj + A(j − 1, Y − wj) }  if wj ≤ Y. 
The solution can then be found by calculating A(n, W). To do this efficiently we can use a table to store previous computations. This solution will therefore run in O(nW) time and O(nW) space, though with some slight modifications we can reduce the space complexity to O(W).

Good luck guys

Link to comment
https://www.neowin.net/forum/topic/699252-algorithm-help/#findComment-590204434
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • This is about the EU given consumers options, Apple is all about not giving options and locking you into its own services, this hurts Apple far more than it hurts the EU market because it makes Apple products look less appealing by Apple refusing to offer its own service because they have to give options to rivals, the end results are consumers might look at alternatives like Android. It's a game Apple can't really win when there are alternatives and Apple will in time change course on this, until then, let Apple hurt themselves in the EU market.
    • Microsoft unveils new Surface Laptop with improved trackpad, Snapdragon X2, and more by Taras Buria Microsoft's new Surface Laptop Ultra generated a lot of buzz earlier this month, but in addition to its most powerful laptop with an NVIDIA chip, Microsoft also has a more affordable laptop lineup, which has been waiting for an update for quite a while. Today, Microsoft announced the eighth-generation Surface Laptop. The new Surface Laptop is powered by the Snapdragon X2 Plus and X2 Elite processors. These chips offer faster CPU performance, up to 58% faster graphics, and 80 TOPS Neural Processing Units (NPUs) for on-device AI processing. Like the previous models, these chips retain their great energy efficiency, and Microsoft says that buyers can expect up to 20 hours of work on a single charge. The laptop is available in two sizes: 13.8-inch and 15-inch. You will have a hard time finding visual differences between the new and previous models, as Microsoft is not taking any major design leaps, except for the new Jade color, which may look familiar to Surface Laptop 5 owners. Other colors include Platinum, Black, and Dune. The 15-inch variant got a higher-resolution display. It is a 3,270 x 2,180 resolution screen with a pixel density of 262 ppi (the 13-inch model has a 201 ppi density) and a maximum brightness of 600 nits SDR and HDR. Unlike the Surface Pro 12th-gen, which is available with optional OLED displays, the Surface Laptop sticks with IPS, a 1,300:1 contrast ratio, a 120Hz refresh rate, and a 3:2 aspect ratio. Another notable change in the Surface Laptop 8 is its trackpad. It now provides haptic feedback when you perform various actions in apps and the operating system. It is a relatively new feature that Microsoft brought to Windows 11 in recent updates, and it is only available on certain devices, such as the Logitech MX Master 4, Surface Slim Pen 2, the upcoming Surface Laptop Ultra, and now the Surface Laptop 8. The new Surface Laptop with the new Surface Pro Like its tablet-shaped sibling, the new Surface Laptop is notably more expensive. It starts at a $1,599 for a 13.8-inch configuration with a 256GB SSD and 16GB of RAM. However, in the US, the base model has double the storage while keeping the same price. Available configurations include up to 64GB of memory and up to 2TB SSD (user-removable PCIe Gen4). The Surface Laptop 8 is now available for purchase on the official Microsoft website.
    • Microsoft announces 12th-gen Surface Pro with Snapdragon X2 processors by Taras Buria So far, 2026 has been rich in Surface announcements. Microsoft started with a fresh lineup of Surface for Business devices powered by Intel's new Core Ultra 300 processors. Then the company revealed the Surface Laptop Ultra, its most powerful laptop with NVIDIA's RTX Spark processor. Now, it is time for new Surface Pro and Surface Laptop models with Qualcomm processors. Microsoft's original Copilot+ PCs with Snapdragon X1 chips debuted in late May 2024. Two years later, Microsoft is finally updating the lineup with new models featuring Snapdragon X2 processors. The 12th-gen Surface Pro continues the well-established formula of Microsoft's flagship tablet, and Microsoft is not even changing colors, as the tablet will be available in three colors: Dune, Black, and Platinum. The most important changes are mostly hidden inside. Microsoft switched from the Snapdragon X1 to the new Snapdragon X2, which promises up to 53% faster graphics performance than the previous generation and up to 15.5 hours of battery life. The built-in NPU is also much more powerful, and it can run at up to 80 TOPS for on-device AI processing. Like before, the new Surface Pro is available with a 13-inch IPS display, and Microsoft is still offering OLED as a separate, more expensive configuration. Speaking of configurations, the Surface Pro will be available with a 10-core Snapdragon X2 Plus or a 12-core Snapdragon X2 Elite. Microsoft expanded the available RAM configurations to 64GB (previously 32GB was the maximum), while storage remains unchanged at 256GB, 512GB, or 1TB of user-replaceable PCIe Gen4 SSDs. The new Surface Pro and the Surface Laptop Other specs remain mostly unchanged. The computer has the same 1440p Windows Hello webcam, two USB4 ports for charging, data, and display output, Wi-Fi 7 and Bluetooth 5.4 support, dual speakers, and compatibility with Surface Pro Signature and Flex keyboards. With that said, there is one very important aspect of the Surface Pro that changed significantly, and it is the price. While the previous-gen Surface Pro launched at $999 for the base configuration, in 2026, the entry-level Surface Pro with Snapdragon X2, 16GB of memory, and 256GB will set you back an eye-watering $1,499. To sweeten the pill, Microsoft is running a limited-time promotion where Surface Pro buyers can get a free Surface Pro 13-inch Keyboard. The promo runs from June 16 through June 30. The new Surface Pro is available now on the official Microsoft Store website.
    • MakeMKV 1.18.4 Beta by Razvan Serea MakeMKV is a format converter, otherwise called "transcoder". It converts the video clips from proprietary (and usually encrypted) disc into a set of MKV files, preserving most information but not changing it in any way. The MKV format can store multiple video/audio tracks with all meta-information and preserve chapters. There are many players that can play MKV files nearly on all platforms, and there are tools to convert MKV files to many formats, including DVD and Blu-ray discs. Additionally MakeMKV can instantly stream decrypted video without intermediate conversion to wide range of players, so you may watch Blu-ray and DVD discs with your favorite player on your favorite OS or on your favorite device. Reads DVD and Blu-ray discs Reads Blu-ray discs protected with latest versions of AACS and BD+ Preserves all video and audio tracks, including HD audio Preserves chapters information Preserves all meta-information (track language, audio type) Fast conversion - converts as fast as your drive can read data. No additional software is required for conversion or decryption. Available for Windows, Mac OS X and Linux Functionality to open DVD discs is free and will always stay free. All features (including Blu-ray decryption and processing) are free during BETA. MakeMKV 1.18.4 changelog: Small improvements and bugfixes Notable bug fixes: Fixed linux armhf binary crash on certain architectures Download: MakeMKV 1.18.4 Beta | 15.7 MB (Free, paid upgrade available) Download: MakeMKV for Mac OS X | 41.9 MB Links: MakeMKV Website | MakeMKV for Linux | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Year In
      Console General earned a badge
      One Year In
    • One Year In
      Twozo Technologies earned a badge
      One Year In
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • Veteran
      branfont went up a rank
      Veteran
  • Popular Contributors

    1. 1
      +primortal
      523
    2. 2
      +Edouard
      209
    3. 3
      PsYcHoKiLLa
      113
    4. 4
      Steven P.
      90
    5. 5
      Nick H.
      71
  • Tell a friend

    Love Neowin? Tell a friend!