Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Introduction

This challenge consists in finding the greatest number removing y digits from the original number n which has x digits.

Assuming y=2 n=5263 x=4, the possible numbers removing y=2 digits are:

[52, 56, 53, 26, 23, 63]

So, the greatest number is 63 which must be the output for this example.


Another logic would be: for each y, search from left to right the digit which right next digit is greater, then remove it, else when no match, remove the last y-digits.

Using y=3 n=76751432 x=8 to explain:

y=3
76751432
-^------ remove 6 because right next 7 is greater

y=2
7751432
---^--- remove 1 because right next 4 is greater

y=1
775432
-----^ the search failed, then remove last y digits

result = 77543

Both methods explained above works.. of course, you can use another method too :)

Challenge

The number n won't have more than 8 digits, and y will always be greater than zero and lower than x.

To avoid strict input format, you can use the values: y n x the way you prefer: as parameters in function, raw input, or any other valid way. Just don't forget to say how you did that in your answer.

The output should be the result number.

This is , the shortest answer in bytes wins.

Example Input and Output

Again: you do not need to be too strict :)

4 1789823 7 -> 983
1 54132 5   -> 5432
3 69314 5   -> 94
2 51794 5   -> 794

Edit

I changed the input order to reflect the fact that some of you may not need the x value to solve the problem. x is now an optional value.

share|improve this question
2  
Please allow more general input and output, requiring a specific string format is usually a bad idea. – xnor Jan 13 at 1:07
1  
@LuisMendo I wouldn't mind editing the I/O in mine. ¯\_(ツ)_/¯ – Alex A. Jan 13 at 1:16
4  
-1 because of the strict I/O requirements, +1 for an interesting challenge. Overall, a solid sidevote. – Mego Jan 13 at 4:39
1  
The input format is too strict as others have said, especially considering that x is kind of a useless information. – Fatalize Jan 13 at 8:10
1  
@Fatalize Actually, I think that depending on the approach you take, having x as input can shorten the code. (Case in point: my Julia answer.) – Alex A. Jan 13 at 16:58

13 Answers 13

up vote 3 down vote accepted

A-Ray, 9 7 bytes

My new language! According to meta, this is allowed, but if this is not accepted, then I will remove it.

pM:i-II

Explanation:

  :i-II       Gets all permutations possible for the given number converted to an array,
                      with the length of y-x, which is the -II part
 M            Gets the maximum of the result above
p             Prints the resulting array above, with no separators

Example input (number, x, y):

1736413 7 4

Output:

764

You can test this with the .jar file given in the github link.

share|improve this answer

MATL, 10 bytes

-jowXncUX>

This uses version (9.2.1) of the language/compiler, which is earlier than this challenge.

It takes three inputs from stdin in this order: string length, number of removed characters, string.

Example

>> matl
 > -jowXncUX>
 > 
> 7
> 4
> 1789823
983

EDIT: Try it online! (the code in the link has XN instead of Xn to conform to changes in the language after this challenge; also, o is not needed anymore)

Explanation

(This still costs 2 bytes more than it should due to Octave's and Matlab's nchoosek function behaving differently. Fixed in the next release of the compiler.)

-        % implicitly input two numbers, and subtract them
jo       % input string, and convert to ASCII codes
wXn      % swap inputs. Generate all combinations, each in a row
c        % convert to char array
U        % convert each row to a number
X>       % get maximum. Implicitly display

Answer to original challenge (stricter input requirements): 16 bytes

jYbZ)b-wowXncUX>

Uses current version (9.2.1) of the language/compiler.

Example

>> matl jYbZ)b-wowXncUX>
> 4 1789823 7
983

Explanation

(This should have been 4 bytes less, but I need that wow...c because Octave's nchoosek function, unlike Matlab's, doesn't work with character input. Will be fixed for next release of the compiler.)

j              % input string
YbZ)           % split at spaces into strings
b-             % subtract first and third (1-digit) strings
wow            % convert middle string into ASCII codes
Xn             % get all combinations, each in a row
c              % convert to char array
U              % convert each row to a number
X>             % get maximum. Implicitly display
share|improve this answer
2  
wow Your code is amazed at its own shortness ;) – ETHproductions Jan 13 at 2:22
2  
@ETHproductions Haha. Well, with the new input requirements it lost 6 bytes and got... speechless – Luis Mendo Jan 13 at 10:44

Pyth - 11 9 8 bytes

eS.cz-QE

Test Suite.

share|improve this answer
    
Nice golf, but doesn't adhere to the input formatting? – Lui Jan 13 at 2:52
    
@Lui oh, didn't see that it was that strict, fixing. – Maltysen Jan 13 at 2:56
    
Fair enough, it looks like there is some discussions about it in the comments on the question itself, but it isn't resolved. – Lui Jan 13 at 2:58
    
@L fixed. SPACE FILLER. – Maltysen Jan 13 at 3:04
    
Looks better, but I think the input also has x on the same line, where x is the number of digits in the main integer? ie: 2 5263 4. – Lui Jan 13 at 3:06

Japt, 19 bytes

Vs ¬àW-U m¬mn n!- g

Try it online!

How it works

        // Implicit: U = y, V = n, W = x
Vs ¬    // Convert V into a string, then split into an array of chars.
àW-U    // Generate all combinations of length W-U.
m¬mn    // Join each pair back into a string, then convert each string to a number.
n!-     // Sort by backwards subtraction (b-a instead of a-b; highest move to the front).
g       // Get the first item in this list.
        // Implicit: output last expression
share|improve this answer

Brachylog, 30 bytes

,{,[N:Y].hs?lL,Nl-Y=L}?:1forh.

Since OP has relaxed the constraints on IO, this expects [Number, NumberOfDigitsRemoved] as input and returns the answer as output, e.g. brachylog_main([1789823,4], Z)..

Explanation

,{                   }?:1f     § Declare sub-predicate 1 and find all inputs which satisfy
                               § this sub-predicate with output = Input of the main predicate
                               § (i.e. [Number, Number of digits to remove])

                               § -- Sub-predicate 1 --
  ,[N:Y].                      § Output = [N, Y]
         hs?                   § Input = a subset of N
            lL,Nl-Y=L          § Length of Input = Length of N - Y

                          orh. § Order the list of answers, reverse it an return the first
                               § element (i.e. the biggest number of the list)
share|improve this answer

Python 3, 69 bytes

This defines an anonymous function accepting all three arguments. Taking full advantage of the rule that "you can use the values: y n x the way you prefer", I have chosen to accept y and x as integers and n as a string. The return value is a string.

from itertools import*
lambda y,n,x:''.join(max(combinations(n,x-y)))

Just in case anyone feels that this is stretching the rules too far, this version takes all inputs as integers and is 74 bytes.

from itertools import*
lambda y,n,x:''.join(max(combinations(str(n),x-y)))

And just for kicks, I also wrote a two-argument version, taking y and n from the command line and printing the result to STDOUT. It's 92 bytes.

import sys,itertools as i
_,y,n=sys.argv
print(*max(i.combinations(n,len(n)-int(y))),sep='')
share|improve this answer

ES6, 70 bytes

r=(y,n)=>y?r(y-1,Math.max(...`${n}`.replace(/./g," $`$'").split` `)):n

Returns a numeric result unless y is falsy and n is a string. I've convinced myself that doing the recursion the wrong way around still works (my solution isn't applicable to doing the correct recursion).

Also my first code golf where I use all three quote signs (although not all as quotes), which prevented me from trivially calculating the length.

share|improve this answer

Julia, 128 95 bytes

f(y,n,x)=maximum(i->parse(join(i)),filter(k->endof(k)==x-y,reduce(vcat,partitions(["$n"...]))))

This is a function that accepts the three values as parameters and returns an integer.

Ungolfed:

function f{T<:Integer}(y::T, n::T, x::T)
    # Get all ordered partitions of the digits of n
    p = reduce(vcat, partitions(["$n"...]))

    # Filter to groups of size x-y
    g = filter(k -> endof(k) == x - y, p)

    # Get the maximum resulting number
    return maximum(i -> parse(join(i)), g)
end
share|improve this answer

Haskell, 64 bytes

import Data.List
y#x=maximum.filter((==x-y).length).subsequences

Usage example: (4#7)"1789823" -> "983".

The original number n is takes as a string. (Not sure if I'm overstressing the "no strict input format" rule, but string input was required(!) in the first version).

How it works: make a list of all subsequences of n, keep those with length x-y and pick the maximum.

share|improve this answer

Ruby, 40 bytes

->y,n,x{n.chars.combination(x-y).max*''}

This is an anonymous function that takes y and x as integers and n as a string, and returns a string. You may call it for instance like this

->y,n,x{n.chars.combination(x-y).max*''}[2,"5263",4]

and it will return "63".

share|improve this answer

MATLAB 40 bytes

@(n,y)max(str2num(nchoosek(n,nnz(n)-y)))

Test:

ans('76751432',3)
ans = 77543
share|improve this answer

Pyth, 45 bytes

=cz)Fk.P@z1-l@z1v@z0I:@z1j".*"k1I>vkZ=Zvk)))Z

try it here

share|improve this answer

JavaScript (ES6), 78

A recursive function with 2 arguments y and d. y can be numeric or string, d must be a string.

r=(y,d)=>y?Math.max(...[...d].map((x,i)=>r(y-1,d.slice(0,i)+d.slice(i+1)))):+d

Before the challenge changed it was 107 - ... with all input/output oddities ...

x=>(r=(n,d)=>n?Math.max(...[...d].map((x,i)=> r(n-1,d.slice(0,i)+d.slice(i+1)))):+d)(...x.match(/\d+/g))+'\n'

Test

r=(y,d)=>y?Math.max(...[...d].map((x,i)=>r(y-1,d.slice(0,i)+d.slice(i+1)))):+d

function test() {
  [a,b]=I.value.match(/\d+/g)
  O.textContent=r(a,b)
}

test()
y,n: <input id=I value='4 1789823' oninput="test()">
<pre id=O></pre>

share|improve this answer
    
Typo: n-1 should be y-1. – Neil Jan 13 at 16:18
    
@Neil fixed, thanks – edc65 Jan 13 at 17:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.