r/dailyprogrammer • u/jnazario 2 0 • Apr 26 '17
[2017-04-26] Challenge #312 [Intermediate] Next largest number
Description
Given an integer, find the next largest integer using ONLY the digits from the given integer.
Input Description
An integer, one per line.
Output Description
The next largest integer possible using the digits available.
Example
Given 292761 the next largest integer would be 296127.
Challenge Input
1234
1243
234765
19000
Challenge Output
1243
1324
235467
90001
Credit
This challenge was suggested by user /u/caa82437, many thanks. If you have a challenge idea, please share it in /r/dailyprogrammer_ideas and there's a good chance we'll use it.
76
Upvotes
11
u/mc_greggers Apr 26 '17 edited Apr 27 '17
O(nlogn)
The idea is to find the last index where a digit is immediately followed by a larger digit - that's the best place to make a change. Then find the smallest following digit which is larger than whatever is in that index, swap that one in, then sort the remaining digits.
Take 124321 - We identify index 1 (holding a 2) as the swap point. The smallest proceeding digit is a 3, so we swap a 3 into index 1. Then we sort the remaining digits (2421) and get 131224.
edit: fixed formatting
10
u/zatoichi49 Apr 26 '17 edited Apr 27 '17
Method:
Add all permutations of the integer into a sorted list (removing any duplicates), then find the index of the original integer in that list and print the next value (at index+1).
Python 3:
Output:
6
u/fsrock Apr 26 '17 edited Apr 26 '17
Java
My second post, i know it's not optimal in any way. But it works(Challenge Input). Any adice to improve this method with Java lang is greatly appreciated.
2
u/KillerCodeMonky Apr 27 '17 edited Apr 28 '17
I pretty disappointed at the number of brute force solutions. This one only requires a little thought to get a O(n) solution.
Method:
EDIT: To clarify, "sort the run ascending" is merely reversing it. Remember that our condition in (4) was to find the descending run. Then (5) and (6) swap an element that maintains that descending order. Reversing is linear, so we avoid the O(n log n) of a proper sort.
Code (PowerShell):
7
u/adrian17 1 4 Apr 26 '17
Brute force Python.
7
u/gabyjunior 1 2 Apr 26 '17 edited Apr 26 '17
Complexity O(n), working on a string of n digits (Narayana Pandita algorithm).
6
u/MattieShoes Apr 26 '17
Seriously?
C++, works on the challenge stuff too.
Output:
3
u/quantik64 Apr 26 '17 edited Apr 26 '17
Intermediate? I AM ASHAMED OF YOU!!!
PYTHON 3
3
u/moeghoeg Apr 27 '17 edited May 02 '17
Python 3. O(n), where n is the number of digits. Finds the last digit x_i in the input number x that is not part of a descending range, reverses the range of digits in x starting at index i+1 and then swaps x_i with the smallest digit x_m, where m > i and x_m > x_i. x_i will end up at the correct position in the ascending range resulting from the reversal.
EDIT: Thanks to /u/KillerCodeMonky, for making me realize that you can just reverse instead of sort! So algorithm is O(n) rather than O(n log n).
2
u/zencoder1 Apr 26 '17
Javascript
Relatively new to programming. Probably not great but it works
2
u/MoltenCookie Apr 27 '17
Python3
Incredibly inefficient, but hey at least it's pretty short!
2
u/NiceGuy_Ty Apr 27 '17
Rust
Made an iterator that can use Narayana Pandita algorithm to generate permutations from a given starting value, and then just advances the iterator by one to get the next largest value.
2
u/neminem1203 Apr 27 '17 edited Apr 27 '17
This is a bit sloppy but it works
the idea is to start from the right and keep going left until the number is less than the previous number. Once you find a number that is lower than the previous number on the right, swap that with the lowest non-zero number and then flip the array on the right. I'm open to suggestions on how to make this code better
Example: 2347650 is the input. 4 is the index of the swap. Swap that with 5 (the lowest non-zero number on the right side). Now you have 235(7640) < now swap this to create the next largest number which is 2350467
2
u/chunes 1 2 Apr 27 '17
Factor
2
u/LenAnderson Apr 27 '17
Groovy
Permutations...
+/u/CompileBot Groovy
2
u/Flynn58 Apr 27 '17 edited Apr 27 '17
Python 3.5
Method: Use itertools to create a set of all permutations of the characters, and sort the set. Find the index of the original number, and output the set entry at the next index.
+/u/CompileBot python3 --time --memory
2
u/yourbank 0 1 Apr 27 '17
clojure
approach
code
2
u/ChazR Apr 27 '17
Haskell
2
u/Minolwa Apr 28 '17
Brute Force Scala
Method:
Sorts permutations of the integers then returns index of the inputs + 1
2
u/mjpalanker May 16 '17
Python3
Uses sorting, not permutations
2
u/skeeto -9 8 Apr 26 '17
C with brute force.
2
u/errorseven Apr 26 '17
AutoHotkey - I didn't code the Function, but I saw others using built in Permutation functions.. meh.
Output:
1
u/Dr_Octagonapus Apr 26 '17 edited Apr 27 '17
Python3
Method: Get a list of all the permutations, remove any that are smaller than the original number, then find the smallest number of the remaining
+/u/CompileBot python 3
1
u/dgreenmachine Apr 26 '17
Python 3, n2 solution
1
u/Scroph 0 0 Apr 26 '17 edited Apr 26 '17
Bruteforce solution.
+/u/CompileBot D
Input :
Edit : CompileBot's DMD version is too old for
permutationsit seems.1
u/ZebbRa Apr 26 '17
Python 3
1
u/[deleted] Apr 26 '17
R
1
u/MightExpunge Apr 26 '17
Python 3
Passes challenge input and can accept user input.
1
u/larkei15 Apr 26 '17
Here is an O(NlogN) solution in C++ as it uses mergesort. I'm sure there are better ways to solve this problem, but this was what I came up with other than brute force.
1
u/bss-applications Apr 27 '17 edited Apr 27 '17
C#
As ever I think I'm missing a bit of math, must be a smarter way of doing this. Works on all but the last output...19000 -> 19001 not 90001. Well, it does containt all the right integers!
Sharp observers will note this is attempt 2. The first attempt I went down a route of building a List of all valid objects and then doing something like
however, that involved filling the array by randomising the input digits and checking each combination was unique. I realised I was heading for computational hell as the number of digits grew...235467 has 6 digits and 720 combinations!
1
u/Tauo Apr 27 '17
Here's my O(n) complexity take on it, implemented in Java.
Going from the rightmost digit, an indexed array of buckets is kept that keeps track of the least significant digit for each integer found. When an integer that is smaller than the current max is found, that digit is swapped with the next largest filled bucket. Everything after the current pointed-at digit is now guaranteed to be in descending order, so the sublist starting after the pointer is reversed to get the smallest integer possible.
1
u/ASpueW Apr 27 '17
Rust
Output:
1
u/[deleted] Apr 27 '17
C#
[Source] (https://gist.github.com/Bambofy/66dbf94d7054038289d4d66d36fbd541)
1
u/moeghoeg Apr 27 '17
Maybe it's my English, but what do you mean by the next largest integer? Is it the smallest integer that is larger than the input integer?
1
u/Godspiral 3 3 Apr 27 '17
in J,
1324
1243 1324 235467 90001
1
u/shinolikesbugs Apr 27 '17
Python 2.7 New to python feedback welcome. I split the input into a list b4 sending it in [int(i) for i in str(1234)]
def GetNextInt(numb):
if len(numb) > 0:
else:
1
u/im_not_awesome Apr 27 '17
Python 3 This is my first post here, I am aware that my solution is most likely very inefficient and sloppy, any suggestions would be welcomed. Input:
Output:
1
u/svgwrk Apr 27 '17
Rust. I use the same brute force-y method everyone else did with regard to permutations: get them all, sort them, deduplicate them, pick the one after the input value.
Permutohedron theoretically offers a "next lexical" option that I wanted to use instead, but it spits out a weird value (1234 -> 3421 ???) and I don't get why, so meh.
1
u/[deleted] Apr 27 '17 edited Apr 27 '17
C++
1
u/ryancav Apr 28 '17
C#, brute force:
1
u/[deleted] Apr 28 '17
Rust 1.16
Still new to Rust, feedback welcome! Method was to permute the input string and then iterate over each permutation filtering out numbers smaller than the original input number, and then finding the smallest number that was in the remaining set.
Output
1
u/MightExpunge Apr 29 '17
Retina
I fixed the redundancies in my previous solution and simultaneously took the opportunity to try a regex-based esolang. My first foray with Retina. Passes all challenge inputs.
Try it online!
Code
1
u/mr_smartypants537 Apr 29 '17
Takes a series of char for input
Method:
C:
1
u/[deleted] Apr 29 '17 edited Apr 29 '17
Java First post, I'm trying to use software engineering principles for the practice. Hence the Javadoc and JUnit usage. Any comments are appreciated. The JUnit test parameters are a little messed as of the ArrayList usage.
Code
JUnit
1
u/buddycool Apr 30 '17 edited Apr 30 '17
New to this thread, I've tried it in JAVA, sorry for indentation(i don't know edit:now I know ;)) :
Thank You !
1
u/YouColinMeOut Apr 30 '17 edited Apr 30 '17
Method
Even though I saw that there is a library function that can complete this challenge, I wanted to devise my own program that only used the general I/O, math, and string libraries. Each number is passed to main as an argument in the console. Since each number passed to the program is parsed as an array of characters, each decimal value is automatically separated.
The separated decimal values allow the program to check the least significant decimal value and swap its value with the next least significant digit that has a lower value. If no digit is found with a lesser value, the program moves on to the next digit and checks it with each higher digit. If the swap occurs with the least two significant digits, then the program prints and moves on to the next integer, otherwise the digits underneath where the least significant digit was placed are sorted by placing the largest digit values in the least significant places.
In the rare case that the digits form a pattern where each less significant digit is less than the previous, the program will print a message that says that the input is the greatest possible value with the given permutation.
Complexity
I believe this is roughly O( n2 ). I used selection sort, which is O( n2 ), as a lazy way of sorting the numbers below the index that is swapped with the least significant digit. I didn't think this would be an issue as the nested for loop in findFirstSwap already limits the complexity to O( n2 ). However since n is the number of decimal places in the number, a large value of n means that the number would also be very large.
Other Remarks
This is my first submission to Daily Programmer and had a lot of fun spending a day working on this. I hope to be as active as I can on this subreddit. I thought that actively participating in this subreddit would help me increase my coding skills and make me a faster programmer as well. So if anyone wants to give me some feedback on my code I'd greatly appreciate it!
C++ Code
1
u/den510 Apr 30 '17
Quick and simple brute force in Ruby.
+/u/CompileBot Ruby
1
u/Vyse007 Apr 30 '17
My answer in Python 2. I found that finding all permutations was just too easy (and probably not the right answer anyway, from an interviewing point of view), so I did it the hard way. There is a minor flaw (see if you can find it!), but it works on the challenge inputs.
1
u/pnossiop May 01 '17
C++
1
u/[deleted] May 01 '17
Not particularly proud of this, but it does work.
Python 3
1
u/Executable_ May 03 '17
Python3
+/u/CompileBot python
1
u/salilotr May 05 '17
Java: Didn't use permutations, solved it by swapping the digits and by maintaining a list of invalid numbers. List gets updated with a digit if no swap takes place in an iteration. Any advice will be much appreciated.
1
u/[deleted] May 07 '17
Scala Find permutations, sort find index and take index + 1
1
u/Xeonfobia May 07 '17 edited May 07 '17
My first time posting here, and my first time programming in Lua! (Lua 5.2), complexity is exponential, help is appreciated.
1
u/rc48 May 09 '17 edited May 10 '17
Ruby - brute force by permutation.
1
u/djfrydog May 10 '17
My Python 2 solution solution using permutations.
Code
import itertools
Quick Unit Test
1
u/rc48 May 10 '17
Ruby - efficient algorithm - includes tests comparing to the permutation algorithm. Would appreciate any feedback.
1
u/polaroid_kidd May 12 '17
Method: Get all permutations by swapping once going left to right and in place crossing.
Github for tests if you want to see
I know the permutation code is ugly, and I'm also not 100% sure why it actually works. Any feedback would be much appreciated!
Java:
1
u/benz05 May 19 '17
Python 3
1
u/Zigity_Zagity Jun 02 '17 edited Jun 02 '17
Python 3, technically runs in n2 (n2 / 2) in the worst case. Algorithm works as following: look at the last number, then compare it against the elements preceding it till we find one smaller than it. Swap those two elements. Break the array into two parts: things before (left of, inclusive) and things after (right of, exclusive) the index of the swapped value. Sort the 'after' array, concatenate the arrays -> answer.
This would be OK if it weren't for the '19000' input - 0 is never higher than anything, so I included another while - if you can't find a value higher than the final, redo it temporarily ignoring the last element (it is included in the sorting as normal though!)
1
u/ChemiCalChems Jun 08 '17
C++ Checks whether the current tested number has the same digits as the number given by user, else increments the number and checks again. Input to be provided as argument to the program.
1
u/IPV4clone Jun 09 '17
C#
Code:
Input/Output:
1
u/santoso-sheep Jun 19 '17
JavaScript:
1
u/bruce3434 Jun 20 '17
D.
The worst case I suppose. Uses permutation. First answer here.
1
u/TheMsDosNerd Jul 29 '17
Here are 2 completely different solutions in Python.
Short but ugly:
More beautiful:
1
u/[deleted] Aug 21 '17 edited Aug 21 '17
Ruby
Uses permutation.
Code:
Output:
1
u/ironboy_ Oct 14 '17
JavaScript
No permutations - just count up to the closest number that contains all the digits.
Output
0
u/[deleted] Apr 26 '17
[deleted] — view deleted comment