Remove digits, retaining greater number

22

2

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.

removed

Posted 2016-01-13T00:05:02.293

Reputation: 2 785

2

Please allow more general input and output, requiring a specific string format is usually a bad idea.

– xnor – 2016-01-13T01:07:05.453

@xnor But some answers have already been posted...? – Luis Mendo – 2016-01-13T01:09:36.933

That's tricky, edits after answers are usually frowned upon. Here, though, I think the input processing is separate enough that answers could change it easily. – xnor – 2016-01-13T01:16:08.483

1@LuisMendo I wouldn't mind editing the I/O in mine. ¯\(ツ) – Alex A. – 2016-01-13T01:16:40.390

Ok, I too will change my answer (tomorrow) if input format is made more flexible. I suggest that at least the current format should continue to be allowed – Luis Mendo – 2016-01-13T01:21:37.293

Just to check, in other words, the problem is to find the size (x-y) substring of n with the greatest numeric value? – Michael Klein – 2016-01-13T02:04:14.433

4-1 because of the strict I/O requirements, +1 for an interesting challenge. Overall, a solid sidevote. – Mego – 2016-01-13T04:39:34.290

1The input format is too strict as others have said, especially considering that x is kind of a useless information. – Fatalize – 2016-01-13T08:10:08.890

Sorry me for that, I didn't know it would impact so much on the answers... I've updated my question – removed – 2016-01-13T08:27:49.463

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. – 2016-01-13T16:58:38.613

@WashingtonGuedes No problem. It's your first question and I think overall you've done a splendid job. :) – Alex A. – 2016-01-13T16:59:14.533

Answers

3

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.

TheCoffeeCup

Posted 2016-01-13T00:05:02.293

Reputation: 626

4

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

Luis Mendo

Posted 2016-01-13T00:05:02.293

Reputation: 87 464

3wow Your code is amazed at its own shortness ;) – ETHproductions – 2016-01-13T02:22:02.407

3@ETHproductions Haha. Well, with the new input requirements it lost 6 bytes and got... speechless – Luis Mendo – 2016-01-13T10:44:15.250

3

Pyth - 11 9 8 bytes

eS.cz-QE

Test Suite.

Maltysen

Posted 2016-01-13T00:05:02.293

Reputation: 25 023

Nice golf, but doesn't adhere to the input formatting? – Lui – 2016-01-13T02:52:55.903

@Lui oh, didn't see that it was that strict, fixing. – Maltysen – 2016-01-13T02:56:50.057

Fair enough, it looks like there is some discussions about it in the comments on the question itself, but it isn't resolved. – Lui – 2016-01-13T02:58:59.943

@L fixed. SPACE FILLER. – Maltysen – 2016-01-13T03:04:44.043

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 – 2016-01-13T03:06:14.927

@Lui OP edited to say it was optional. – Maltysen – 2016-01-13T03:08:59.303

Ah, okay, I didn't see that sorry. Nice work! – Lui – 2016-01-13T03:09:42.443

The OP was edited. Strict formatting is not needed now, so you can probably just do eS.cQ-lQE and take the input like n\ny. – PurkkaKoodari – 2016-01-13T09:08:12.723

1

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

Alex A.

Posted 2016-01-13T00:05:02.293

Reputation: 23 761

1

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

ETHproductions

Posted 2016-01-13T00:05:02.293

Reputation: 47 880

1

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)

Fatalize

Posted 2016-01-13T00:05:02.293

Reputation: 32 976

1

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='')

Tim Pederick

Posted 2016-01-13T00:05:02.293

Reputation: 1 411

1

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.

Neil

Posted 2016-01-13T00:05:02.293

Reputation: 95 035

1

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.

nimi

Posted 2016-01-13T00:05:02.293

Reputation: 34 639

1

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".

daniero

Posted 2016-01-13T00:05:02.293

Reputation: 17 193

1

MATLAB 40 bytes

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

Test:

ans('76751432',3)
ans = 77543

brainkz

Posted 2016-01-13T00:05:02.293

Reputation: 349

0

Pyth, 45 bytes

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

try it here

JuanPotato

Posted 2016-01-13T00:05:02.293

Reputation: 399

0

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>

edc65

Posted 2016-01-13T00:05:02.293

Reputation: 31 086

Typo: n-1 should be y-1. – Neil – 2016-01-13T16:18:51.097