34
\$\begingroup\$

As code-golfers, we're not used to releasing (surely). We're gonna need a few tools to help us do that.

Of course, to help marketing a new release, we need a nice and shiny Release Version. Who doesn't get excited when they hear about version 3.0.0?

Task

Your task will be to write a program/routine/... to increment a version number.

You need to increment the version number and reset the "less important" ones (i.e. patch version).

You get two arguments: the current version (ex "1.0.3") as a string, and an index to know which one to update (0 or 1-indexed).

Example, 0-indexed:

next-version("1.0.3", 0) # 2.0.0
next-version("1.2.3.4.5", 2) # 1.2.4.0.0
next-version("10.0", 0) # 11.0
next-version("3", 0) # 4
next-version("1", 7) # ERROR
next-version("01", 0) # ERROR

The version is a string, each part is a number, separated with a dot. There can be no leading, no trailing or no consecutive dots (and nothing outside of numbers/dots). There is no limit to the size of the version string.

^[1-9]\d*(\.[1-9]\d*)*$

The error case (last two examples) is undefined behavior. What happens in case of wrong inputs is of no relevance to this challenge.

As usual, standard loopholes are forbidden. You're allowed to print or return the string.

\$\endgroup\$
  • 1
    \$\begingroup\$ Can we ask to receive as input first the index and then the version number? \$\endgroup\$ – Leo Dec 8 '16 at 18:10
  • \$\begingroup\$ @Leo yes, the order is not an issue. \$\endgroup\$ – Ven Dec 8 '16 at 18:17
  • \$\begingroup\$ I might add a test case for incrementing the final number in the string, or an example or something to test for. \$\endgroup\$ – nmjcman101 Dec 8 '16 at 18:44
  • \$\begingroup\$ @nmjcman101 how is it a special case? \$\endgroup\$ – Ven Dec 8 '16 at 18:52
  • 3
    \$\begingroup\$ I wish I could make the same challenge with the win condition as "most readable" so someone would write these for me to use in real work. =) \$\endgroup\$ – jpmc26 Dec 8 '16 at 21:25

28 Answers 28

12
\$\begingroup\$

Japt, 16 11 bytes

¡V«´V+ÂX}'.

Test it online! Input number is 1-indexed.

Based on my JavaScript answer. This takes advantage of one of Japt's most helpful features: splitting one string on another before mapping each item, then joining on that string again after mapping.

Ungolfed and explanation

¡  V«  ´ V+Â X}'.
Um@V&&!--V+~~X}'.
                   Implicit: U = input string, V = input number
Um@           }'.  Split U at periods, then map each item X by this function:
   V&&               If V is 0, return V.
      !--V+~~X       Otherwise, decrement V and return X + !V (increments X iff V was 1).
               '.  Re-join the result with periods.
                   Implicit: output last expression
\$\endgroup\$
  • 2
    \$\begingroup\$ A sweet feature indeed! \$\endgroup\$ – Jonathan Allan Dec 8 '16 at 17:50
  • 1
    \$\begingroup\$ Well drat, I thought I had it in the bag. Excuse me, I'm gonna go obsess over my V answer and squeeze every last little byte out of it. :P \$\endgroup\$ – DJMcMayhem Dec 8 '16 at 21:54
11
\$\begingroup\$

Vim 20 25 bytes

I unfortunately realized that it didn't handle the case of updating the last number, so I had to add bytes. This is 1-indexed.

DJA.0@"t.qq2wcw0@qq@qx

TryItOnline

Unprintables:

DJA.^[0@"t.^Aqq2wcw0^[@qq@qx

This takes the arguments in reverse order, as separate lines:

3
1.2.3.4.5

Explanation:

DJ                           # Delete the input argument, and join lines
  A.^[0                      # Add a period to the end
       @"t.                  # Move to the "Copy register"th period
           ^A                # Increment the number under the cursor
             qq       @qq@q  # Until an error
               2w            # Move the cursor forward to the next number
                 cw0^[       # Change the number to 0
                           x # Delete the last '.'
\$\endgroup\$
  • 1
    \$\begingroup\$ Nice! An explanation would be helpful \$\endgroup\$ – Kritixi Lithos Dec 8 '16 at 17:58
  • \$\begingroup\$ @KritixiLithos Added. Unfortunately I had to add some bytes also to handle incrementing the final version number, but it happens. \$\endgroup\$ – nmjcman101 Dec 8 '16 at 18:52
  • \$\begingroup\$ I think if you went 0-indexed, you could just do DJ@"t.<C-a>qq2wcw0<esc>@qq@q which is back down to twenty \$\endgroup\$ – DJMcMayhem Dec 8 '16 at 19:35
  • \$\begingroup\$ @DJMcMayhem I don't think I can do that because then I wouldn't be able to differentiate 0 and 1. \$\endgroup\$ – nmjcman101 Dec 8 '16 at 19:42
  • 1
    \$\begingroup\$ Oh yeah, good point. How about DJ@"f.@"<esc><C-a>qq2wcw0<esc>@qq@q ? \$\endgroup\$ – DJMcMayhem Dec 8 '16 at 19:43
11
\$\begingroup\$

JavaScript (ES6), 44 42 40 37 bytes

Saved 3 bytes thanks to @Neil

x=>i=>x.replace(/\d+/g,n=>i&&+n+!--i)

Input number is 1-indexed.

Test snippet

f = x=>i=>x.replace(/\d+/g,n=>i&&+n+!--i)

console.log(f("1.0.3")(1))
console.log(f("1.2.3.4.5")(3))
console.log(f("10.0")(1))
console.log(f("1")(8))

\$\endgroup\$
  • 2
    \$\begingroup\$ Crossed out 44 is still 44 :) \$\endgroup\$ – Kritixi Lithos Dec 8 '16 at 16:55
  • 1
    \$\begingroup\$ @KritixiLithos What is wrong with my browser? cubeupload.com/im/ofJySU.png \$\endgroup\$ – Gustavo Rodrigues Dec 8 '16 at 17:20
  • \$\begingroup\$ n=>i&&+n+!--i \$\endgroup\$ – Neil Dec 8 '16 at 20:32
  • \$\begingroup\$ @Neil Thanks! I just couldn't figure out how to golf that expression any further... \$\endgroup\$ – ETHproductions Dec 8 '16 at 21:29
10
\$\begingroup\$

V, 13, 12 bytes

Àñf.ñò2wcw0

Try it online!

This is 0-indexed.

There is a ctrl-a (ASCII 0x01) in there, so here is a readable version:

Àñf.ñ<C-a>ò2wcw0

Explanation:

À                   " 'arg1' times
 ñ  ñ               " Repeat the following:
  f.                "   Move to the next '.' character
     <C-a>          " Increment the next number
          ò         " Recursively:
           2w       "   Move two words forward
              cw    "   Change this word
                0   "   to a '0'
\$\endgroup\$
7
\$\begingroup\$

Perl, 40 37 34 + 1 = 35 bytes

-2 bytes thanks to @Dada. -3 bytes thanks to an idea I got from reading @ETHproductions's Japt code.

Run with the -p flag.

$a=<>;s/\d+/$a--<0?0:$&+!($a+1)/ge

Try it online!

Breakdown of the code

-p          #Wraps the program in a while(<>){ ... print$_} statement.
            #Input is read into the $_ variable
$a=<>;s/\d+/$a--<0?0:$&+!($a+1)/ge
$a=<>;                              #Reads the version update into $a
      s/   /                   /ge  #Substitution regex:
                                g   #Repeats the substitution after first match
                                 e  #Interprets replacement as Perl code
       \d+                          #Matches 1 or more digits, and stores match in $&
                  ? :               #Ternary operation
            $a--<0                  #Checks if $a is negative and then decrements $a
                  ?0                #If negative, we've passed our match; print 0 instead
                    :$&+!($a+1)     #Otherwise, we're either printing $& + 0 (if $a was positive) or $& + 1 (if $a was 0).
#Since substitution implicitly modifies $_, and -p prints $_, it prints our answer
\$\endgroup\$
  • \$\begingroup\$ Remove all those parenthesis on both sides! (and $& instead of $1 then) \$\endgroup\$ – Dada Dec 8 '16 at 16:54
  • \$\begingroup\$ I knew I was missing something! Thanks! \$\endgroup\$ – Gabriel Benamy Dec 8 '16 at 16:57
  • \$\begingroup\$ Using 1-indexed numbers can save 4 bytes: Try it online! \$\endgroup\$ – Xcali Apr 11 at 20:52
5
\$\begingroup\$

Jelly, 19 17 bytes

ṣ”.V€‘⁹¦µJ’<⁹×j”.

1-indexed.

TryItOnline!

How?

ṣ”.V€‘⁹¦µJ’<⁹×j”. - Main link: currentVersion, theIndex
ṣ”.               - ṣplit left (currentVersion) at occurences of '.'
   V€             - eVal €ach (creates a list of integers)
      ⁹           - right argument (theIndex)
       ¦          - apply to given index(es)
     ‘            -    increment
        µ         - monadic chain separation (call the above result z)
         J        - range(length(z))  i.e. ([1,2,3,...,length])
          ’       - decrement         i.e. ([0,1,2,...,length-1])
            ⁹     - right argument (theIndex)
           <      - less than?        i.e. ([1,1,...,(1 at theIndex),0...,0,0,0]
             ×    - multiply by z (vectortises) - zeros out all of z after theIndex
              j”. - join with '.'
\$\endgroup\$
  • 3
    \$\begingroup\$ Congrats on 10k!! \$\endgroup\$ – Luis Mendo Dec 8 '16 at 18:18
  • \$\begingroup\$ Can't wait for Jelly 2.0 so you can get rid of that V€ :). \$\endgroup\$ – Ven Dec 8 '16 at 18:28
  • \$\begingroup\$ @LuisMendo - thanks! I'm so unobservant (Dennis noticed my 1K milestone before I did too). \$\endgroup\$ – Jonathan Allan Dec 8 '16 at 18:38
5
\$\begingroup\$

MATLAB, 85 bytes

function f(s,j);a=split(s,'.');a(j)=string(double(a(j))+1);a(j+1:end)='0';join(a,'.')

One based, and first attempt at golf!

\$\endgroup\$
  • \$\begingroup\$ Well done! First time I see the new string type in action :-) \$\endgroup\$ – Luis Mendo Dec 9 '16 at 10:38
5
\$\begingroup\$

C# 116 104 Bytes

using System.Linq;(v,i)=>string.Join(".",v.Split('.').Select(int.Parse).Select((x,n)=>n==i?x+1:n>i?0:x));

Explanation

using System.Linq;(v,i)=>   //Anonymous function and mandatory using
    string.Join(".",                    //Recreate the version string with the new values
        v.Split('.')                    //Get individual pieces
            .Select(int.Parse)          //Convert to integers
                .Select(            
                    (x,n)=>             //Lambda with x being the part of the version and n being the index in the collection
                        n==i                    
                            ?x+1        //If n is the index to update increment x
                            :n>i        //Else if n is greater than index to update
                                ?0      //Set to zero
                                :x));   //Otherwise return x

Try it here

\$\endgroup\$
  • \$\begingroup\$ You don't need the string and int in the anonymous function signature \$\endgroup\$ – TheLethalCoder Dec 9 '16 at 10:39
  • \$\begingroup\$ @TheLethalCoder ahh yes of course, thanks. \$\endgroup\$ – Phaeze Dec 9 '16 at 16:19
4
\$\begingroup\$

Python 2, 84 Bytes

I feel like this could really be shorter.. Might need a way to have a non-enumerate option.

lambda s,n:'.'.join(str([-~int(x)*(i==n),x][i<n])for i,x in enumerate(s.split('.')))

If we were able to take the version as a list of strings, there's a 75-byte solution:

g=lambda s,n:(str(-~int(s[0]))+'.0'*~-len(s))*(n<1)or s[0]+'.'+g(s[1:],n-1)

Furthermore, if both the input and output were lists of numbers, there's a 64-byte solution:

g=lambda s,n:([-~s[0]]+[0]*~-len(s))*(n<1)or [s[0]]+g(s[1:],n-1)
\$\endgroup\$
4
\$\begingroup\$

V 14 20 bytes

Again, I had to add code for the corner case of incrementing the final digit. (1-indexed)

DJA.0@"t.ò2wcw0òx

TryItOnline

Unprintables:

DJA.^[0@"t.^Aò2wcw0^[òx

This takes the arguments in reverse order, as separate lines:

3
1.2.3.4.5
\$\endgroup\$
  • 1
    \$\begingroup\$ Nice answer! I'm always happy to see someone else use V! Just so you know, if you put the first input in 'args', it will predefine register 'a' to that number, so you could do @a (or even shorter, À) which should save you a bunch of bytes. \$\endgroup\$ – DJMcMayhem Dec 8 '16 at 19:18
4
\$\begingroup\$

Batch, 119 bytes

@set s=%1
@set i=%2
@set t=
@for %%i in (%s:.=,%)do @set/an=!!i*(%%i+!(i-=!!i))&call set t=%%t%%.%%n%%
@echo %t:~1%

1-indexed.

\$\endgroup\$
4
\$\begingroup\$

Perl 6, 67 bytes, 0-indexed

->$v,$i {$v.split('.').map({++$>$i??($++??0!!$_+1)!!$_}).join: '.'}

Explanation:

->$v,$i {$v.split('.').map({++$>$i??($++??0!!$_+1)!!$_}).join: '.'}
->$v,$i {                                                         } # function taking version/index to increment
         $v.split('.')                                              # split by dot
                      .map({                          })            # for each version number
                            ++$>$i??                                # if an anonymous variable ($), incremented,
                                                                    #  is greater than $i (index to increment)
                                    ($++??       )                  # if it's not the first time we've been over $i
                                                                    # (using another anonymous value, which gets default-init'd to 0)
                                          0                         # then 0 (reset lower version numbers)
                                           !!$_+1                   # otherwise, increment the number at $i
                                                  !!$_              # otherwise return the number part
                                                        .join: '.'  # join with a dot
\$\endgroup\$
  • 3
    \$\begingroup\$ Just fyi, self answers are totally eligible. In fact, they're even encouraged \$\endgroup\$ – DJMcMayhem Dec 8 '16 at 16:36
  • \$\begingroup\$ @DJMcMayhem I knew about this, but I thought they were not eligible \$\endgroup\$ – Ven Dec 8 '16 at 16:47
3
\$\begingroup\$

PowerShell 3+, 75 74 bytes

($args[0]-split'\.'|%{$m=!$b;$b=$b-or$args[1]-eq$i++;(+$b+$_)*$m})-join'.'

Ungolfed

(
    $args[0] -split '\.' | 
        ForEach-Object -Process {
            $m= -not $b
            $b = $b -or ($args[1] -eq $i++)
            (([int]$b) + $_) * $m
        }
) -join '.'

Explanation

Parameters are accepted using the $args array.

  1. Split the version string on ., then for each element:
    1. $m is set to be -not $b. On first run, $b will be undefined which will be coalesced to $false, so $m will start as $true. $m is intended to be a multiplier that's always 0 or 1 and it will be used later. $m must be evaluated here because we want it to be based on the last iteration's $b value.
    2. $b is set to itself -or the result of comparing an iterator $i with $args[1] (the index parameter). This means $b will be set to $true here once we're on the element that is to be incremented. Additionally, it will be $true in every subsequent iteration because the conditional is -or'd with its current value.
    3. $b is converted to a number using unary + ($false => 0, $true => 1), then added to the current version element $_ which is a [string], but PowerShell always tries to coalesce the argument on the right to the type on the left, so arithmetic will be performed, not string concatenation. Then this value will be multiplied by $m, which is still [bool] but will be implicitly coalesced.
  2. Re-join the resulting array with ..

So, the first iteration where $b becomes $true, $b would have been $false when $m was evaluated, making $m equal $true, which will keep the multiplier at 1.

During that run $b becomes $true and is added to the version element (as 1), thereby incrementing it, and since the multiplier is still 1, that will be the end result.

So on the next iteration, $b will already be $true, making $m equal $false, which will make the multiplier 0. Since $b will forever be $true now, the multiplier will always be 0, so every element returned will be 0 too.

\$\endgroup\$
2
\$\begingroup\$

R, 100 95 92 86 bytes

Unusually for R, this uses 0-indexing. Anonymous function with two arguments (a string and an integer). Likely can be golfed down a tad.

function(v,i)cat((x=scan(t=el(strsplit(v,"\\."))))+c(rep(0,i),1,-x[-(0:i+1)]),sep=".")
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 22 bytes

'.¡vy²N‹i0*}²NQi>})'.ý

Try it online!

I don't know how to do if-else in 05AB1E, so this is longer than it should be.

\$\endgroup\$
  • 1
    \$\begingroup\$ If I'm not misunderstanding, I don't think this works. The question says you have to 0-out the minor versions, so 1.0.0.0.3, 3 should produce 1.0.0.1.0 not 1.0.0.1.3. \$\endgroup\$ – LambdaBeta Dec 8 '16 at 17:05
  • \$\begingroup\$ @LambdaBeta misread, fixed. \$\endgroup\$ – Magic Octopus Urn Dec 8 '16 at 17:37
2
\$\begingroup\$

Coffee-script: 77 67 Bytes

f=(p,i)->((z<i&&v||z==i&&~~v+1||0)for v,z in p.split '.').join '.'

Woot! Time for cake and coffee for the beta release.

Thanks to @ven and @Cyoce I shaved 10 Bytes!

\$\endgroup\$
  • \$\begingroup\$ Nice! Not sure you need the parseInt here though? \$\endgroup\$ – Ven Dec 8 '16 at 22:25
  • \$\begingroup\$ Btw you can save two bytes by using parenless calls (i.e. .join '.' or .split '.') \$\endgroup\$ – Ven Dec 8 '16 at 22:26
  • \$\begingroup\$ Use + instead of parseInt (use ~~ if you need it to be cast to integer) \$\endgroup\$ – Cyoce Dec 9 '16 at 0:21
2
\$\begingroup\$

Python 3, 89 86 bytes

lambda v,c:'.'.join((str((int(x)+1)*(i==c)),x)[i<c]for i,x in enumerate(v.split('.')))

very naive way of getting things done

Edit: rewritten the conditional by referring to @kade

\$\endgroup\$
2
\$\begingroup\$

PHP, 81 bytes

awfully long. At least: the Elephpant still beats the Python.

foreach(explode(".",$argv[1])as$i=>$v)echo"."[!$i],($i<=$n=$argv[2])*$v+($i==$n);

loops through first argument split by dots: "."[!$i] is empty for the first and a dot for every other element; ($i<=$n) and ($i==$n) are implicitly cast to integer 0 or 1 for integer arithmetics.

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 57 55 bytes

(s,x)=>s.split`.`.map((j,i)=>i==x?+j+1:i>x?0:j).join`.`

Examples:

n=(s,x)=>s.split`.`.map((j,i)=>i==x?+j+1:i>x?0:j).join`.`

console.log(n('1.0.3', 0))
console.log(n('1.2.3.4.5', 2))
console.log(n('10.0', 0))
console.log(n('3', 0))
console.log(n('1', 7))

Not the best JS implementation but it's fairly simple and follows the logic you'd expect.

\$\endgroup\$
  • \$\begingroup\$ Okay, that wasn't terribly clear, thanks. \$\endgroup\$ – Florrie Dec 11 '16 at 13:54
1
\$\begingroup\$

Pyth - 21 bytes

j\.++<Kcz\.Qhs@KQmZ>K

Test Suite

\$\endgroup\$
  • 3
    \$\begingroup\$ No, this isn't quite correct. Your 10.0 test case gives 11.0.0, that's one too many part! \$\endgroup\$ – Ven Dec 8 '16 at 17:40
1
\$\begingroup\$

Powershell, 80 100 95 92 Bytes

Saved 5 bytes by using a const for the -1..if

Saved 3 bytes by using !$b instead of $b-eq0

filter x($a,$b){[int[]]$y=$a.Split('.');-1..((-$b,-1)[!$b])|%{$y[$_]=0};$y[$b]++;$y-join'.'}

Explanation:

filter x($a,$b){
    [int[]]$y=$a.Split('.') #Split input into integer array
    $y[$b]++ #Increment 'major' version no. ($b) by one
    -1..((-$b,-1)[!$b])|%{$y[$_]=0} #Set all trailing numbers to 0, now also checks for $b=0 cases.
    $y-join'.' #Join back into '.' seperated Array
}

Test Cases:

x "1.0.3" 0
x "1.2.3.4.5" 2
x "10.0" 0
x "1" 7
2.0.0
1.2.4.0.0
11.0
Index was outside the bounds of the array.
\$\endgroup\$
  • \$\begingroup\$ Nice! I love seeing more powershell here. \$\endgroup\$ – briantist Dec 8 '16 at 23:43
  • \$\begingroup\$ @briantist honestly a lightweight uncompiled version of C# which can interface with everything is a godsend, I deal with a lot of Microsoft stuff at work and absolutely love it. \$\endgroup\$ – colsw Dec 9 '16 at 0:24
  • \$\begingroup\$ Oh absolutely; PowerShell is my jam, but not a lot of people think to use it for golfing. It has some features that are great for golfing, and others that make it suck for golfing, but overall it's a solid choice! I'm toying with the idea of doing a presentation about golfing in PowerShell at my next PSUG. \$\endgroup\$ – briantist Dec 9 '16 at 0:27
  • \$\begingroup\$ @briantist the default aliases are beautiful, but I'd love to be able to use a pre-defined set of a few common commands as single char aliases f for golfing, if say it could compete with some actual golfing languages if we could use r instead of random \$\endgroup\$ – colsw Dec 9 '16 at 0:31
  • \$\begingroup\$ Funny thing about random, it's not an an alias! It's a result of PowerShell's command evaluation. As it looks to find a command in aliases, functions, cmdlets, native applications, etc., the very last thing it tries to do is prepend Get- to whatever it is. So you're actually calling Get-Random, but technically not as an alias. You can see this working by running service, or childitem, or for maximum irony, alias. \$\endgroup\$ – briantist Dec 9 '16 at 0:35
1
\$\begingroup\$

Objective-C 531 Bytes

#import<Foundation/Foundation.h>
int main(int argc,const char *argv[]){@autoreleasepool{NSString *s=[NSString stringWithUTF8String:argv[1]];NSInteger n=strtol(argv[2],NULL,0);NSArray *c=[s componentsSeparatedByString:@"."];if(c.count<=n)NSLog(@"ERROR");else{int i=0;NSMutableString *v=[[NSMutableString alloc]init];for(;i<n;++i)[v appendFormat:@"%@.",[c objectAtIndex:i]];[v appendFormat:@"%li", strtol(((NSString *)[c objectAtIndex:i++]).UTF8String,NULL,0)+1l];for(;i<c.count;++i)[v appendString:@".0"];NSLog(@"%@",v);}}return 0;}

compile:

clang -fobjc-arc -Os main.m -o main

usage:

./main 1.2.3 1
\$\endgroup\$
  • \$\begingroup\$ Welcome to CodeGolf. In the title, You should tell the size of the source code, not the byte code. And the source should, of course, be as short as possible (no unnecessary whitespace, single character variable names etc.). Good Luck. \$\endgroup\$ – Titus Dec 9 '16 at 17:45
  • \$\begingroup\$ can probably use 0 instead of NULL and remove the return 0; at the end of the main. NSString *s can probably have the space removed. **argv is 1 byte shorter than *argv[]. @autoreleasepool{} is probably unnecessary. \$\endgroup\$ – Ven Mar 12 at 9:31
1
\$\begingroup\$

Javascript ES6: 60 bytes

n.split(".").map((n,r)=>{return r>i?n=0:n}).join("."),n[i]++}
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! This doesn't seem to be valid, as it is does not take input in any way, and there is an extra } at the end. On golfing: one of the features of arrow functions is implicit return, so you can replace (n,r)=>{return r>i?n=0:n} with (n,r)=>r>i?n=0:n to save some bytes. \$\endgroup\$ – ETHproductions Dec 10 '16 at 22:21
1
\$\begingroup\$

R, 75 bytes

f=function(a,b){n=scan(t=a,se=".");m=-n;m[b]=1;m[1:b-1]=0;cat(n+m,sep=".")}

Indexing is 1-based. You can play with it online here.

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog), 31 bytes

Requires ⎕IO←0 (Index Origin 0), which is default on many systems. Full program body; prompts for text input (version) and then numeric input (index).

' '⎕R'.'⍕⎕(⊢∘≢↑↑,1+⊃)⊃⌽'.'⎕VFI⍞

Try it online!

 prompt for text input

'.'⎕VFIVerify and Fix Input using period as field separator (fields' validities, fields' values)

 reverse (to put the values in front)

 pick the first (the values)

⎕(...) apply the following tacit function to that, using evaluated input as left argument:

To explain the non-tacit equivalents of each function application we will now use to indicate the left argument (the index) and to indicate the right argument (the list of individual numbers of the originally inputted current version number).

 equivalent to (⍺⊃⍵) use to pick an element from

1+ add one to that 

↑, equivalent to (⍺↑⍵), prepend numbers taken from

⊢∘≢↑ equivalent to (⍺⊢∘≢⍵)↑ equivalent to (≢⍵)↑ take as many numbers from that as there are elements in , padding with zeros if necessary

 format (stringify with one space between each number)

' '⎕R'.' PCRE Replace spaces with periods

\$\endgroup\$
1
\$\begingroup\$

Java 8, 130 bytes

s->n->{String r="",a[]=s.split("\\.");for(int l=a.length,i=-1;++i<l;)r+=(i>n?0:new Long(a[i])+(i<n?0:1))+(i<l-1?".":"");return r;}

Explanation:

Try it here.

s->n->{                 // Method with String and Integer parameters and String return-type
  String r="",          //  Result-String
  a[]=s.split("\\.");   //  String-array split by the dots
  for(int l=a.length,   //  Length of the array
      i=-1;++i<l;)      //  Loop from 0 to `l` (exclusive)
    r+=                 //   Append the result-String with:
       (i>n?            //    If index `i` is beyond input `n`:
        0               //     Append a zero
       :                //    Else:
        new Long(a[i])  //     Convert the current String to a number
        +(i<n?          //     If index `i` is before input `n`
           0            //      Leave the number the same by adding 0
          :             //     Else:
           1))          //      Add 1 to raise the version at index `n`
       +(i<l-1?         //    If we've haven't reached the last iteration yet:
          "."           //     Append a dot
         :              //    Else:
          ""            //     Append nothing
   );                   //  End of loop
   return r;            //  Return the result-String
}                       // End of method
\$\endgroup\$
1
\$\begingroup\$

LiveScript, 53 52 bytes

->(for e,i in it/\.
 [+e+1;0;e][(i>&1)+2*(i<&1)])*\.

-1 byte thanks to @ASCII-only!

Old Explanation:

(a,b)->x=a/\.;x[b]++;(x[to b] ++ [0]*(x.length-1-b))*\.
(a,b)->                                                 # a function taking a and b (version and index)
       x=a/\.;                                          # split a on dot, store in x
              x[b]++;                                   # increment at the given index
                     (x[to b]                           # slice be from 0 to the index
                              ++                        # concat (both spaces are necessary so it's not interpreted as an increment operator
                                 [0]*(x.length-1-b))    # with enough zeros to fill the array back to its original size (x's size)
                                                    *\. # join on dot

Another self-answer... Not that anyone golfes in LiveScript anyway. :P

I was working on another version:

(a,b)->(a/\.=>..[b]++;..[b to *]=0)*\.

But * is too overloaded to be recognized in a splicing index, thus =0 will try to access 0[0]. So you need to write something like ..[b to ..length- b]=[0]*(..length-1-b) and it's longer in the end.

\$\endgroup\$
  • 1
    \$\begingroup\$ sadly f=(a,b)->(for e,i in a/\.<newline> if i<b then e else if i>b then 0 else+e+1)*\. is way longer :( \$\endgroup\$ – ASCII-only Apr 11 at 13:05
  • \$\begingroup\$ @ASCII-only I think it's possible to compress if i<b then e else if i>b then 0 else+e+1 in i.e. [+e+1;0;e;e][i>b+(2*i<b)] or something along those lines, maybe even ([+e;-1][i>b+(2*i<b)]||e-1)+1 \$\endgroup\$ – Ven Apr 11 at 13:08
  • \$\begingroup\$ (a,b)->(for e,i in a/\.<newline> [+e+1;0;e][(i>b)+2*(i<b)])*\., 54 \$\endgroup\$ – ASCII-only Apr 11 at 13:31
  • \$\begingroup\$ Then let's remove the signature: ->(for e,i in it/\.<newline> [+e+1;0;e][(i>&1)+2*(i<&1)])*\. for 52 \$\endgroup\$ – Ven Apr 11 at 13:39
  • \$\begingroup\$ btw you can replace ; with space. also... looks like that's basically as far down as it'll go with this approach \$\endgroup\$ – ASCII-only Apr 11 at 13:41
1
\$\begingroup\$

Haskell, 136 129 bytes

import Data.List.Split
import Data.List
f s n|(x,z:y)<-splitAt n(splitOn "."s)=intercalate "."(x++[show$read z+1]++map(\_->"0")y)

Try it online!


Original

\$\endgroup\$
  • \$\begingroup\$ 128 \$\endgroup\$ – ASCII-only Apr 14 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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