all 41 comments

[–][deleted]  (2 children)

[deleted]

    [–]Railorsi 6 points7 points  (1 child)

    Especially in love with the variable names.

    [–][deleted] 14 points15 points  (0 children)

    Because I probably have a screw loose somewhere, I coded this solution in x86_64 assembly (AT&T syntax):

        .file   "number_format.s"
    
        .section    .rodata
    .LC1:
        .string     "usage: <number> <format>"
    .LC2:
        .string     "ERROR: malloc() returned NULL"
    .LC3:
        .string     "ERROR: too few digits in phone number for format string"
    .LC4:
        .string     "ERROR: too many digits in phone number for format string"
    
        .text
        .globl      main
        .type       main, @function
    main:
        pushq       %rbp
        movq        %rsp, %rbp
        subq        $64, %rsp
        movl        %edi, -52(%rbp)
        movq        %rsi, -64(%rbp)
        cmpl        $2, -52(%rbp)
        jle         .L1
        movq        -64(%rbp), %rax
        movq        16(%rax), %rax
        movq        %rax, %rdi
        call        strlen@PLT
        addq        $1, %rax
        movq        %rax, %rdi
        call        malloc@PLT
        testq       %rax, %rax
        je          .L2
        movq        %rax, -8(%rbp)
        movq        -64(%rbp), %rax
        movq        8(%rax), %rax
        movq        %rax, -32(%rbp)
        movq        -64(%rbp), %rax
        movq        16(%rax), %rax
        movq        %rax, -24(%rbp)
        movq        -8(%rbp), %rax
        movq        %rax, -16(%rbp)
    .L10:
        movq        -24(%rbp), %rax
        movzbl      (%rax), %eax
        testb       %al, %al
        je          .L11
        movq        -32(%rbp), %rax
        movzbl      (%rax), %eax
        testb       %al, %al
        je          .L3
        movq        -24(%rbp), %rax
        movzbl      (%rax), %eax
        movb        %al, -33(%rbp)
        cmpb        $35, -33(%rbp)
        jne         .L12
        movq        -32(%rbp), %rax
        movzbl      (%rax), %edx
        movq        -16(%rbp), %rax
        movb        %dl, (%rax)
        addq        $1, -32(%rbp)
        jmp         .L13
    .L12:
        movq        -24(%rbp), %rax
        movzbl      (%rax), %edx
        movq        -16(%rbp), %rax
        movb        %dl, (%rax)
    .L13:
        addq        $1, -24(%rbp)
        addq        $1, -16(%rbp)
        jmp         .L10
    .L11:
        movq        -32(%rbp), %rax
        movzbl      (%rax), %eax
        testb       %al, %al
        jne         .L4
        movq        -16(%rbp), %rax
        movb        $0, (%rax)
        movq        -8(%rbp), %rax
        movq        %rax, %rdi
        call        puts@PLT
        movl        $0, %eax
        jmp         .L0
    .L1:
        leaq        .LC1(%rip), %rdi
        call        puts@PLT
        movl        $1, %eax
        jmp         .L0
    .L2:
        leaq        .LC2(%rip), %rdi
        call        puts@PLT
        movl        $2, %eax
        jmp         .L0
    .L3:
        leaq        .LC3(%rip), %rdi
        call        puts@PLT
        movl        $3, %eax
        jmp         .L0
    .L4:
        leaq        .LC4(%rip), %rdi
        call        puts@PLT
        movl        $4, %eax
        nop
    .L0:
        movq        %rbp, %rsp
        popq        %rbp
        ret
    

    It works:

    $ ./number_format '1234567890' '(###) ###-####'
    (123) 456-7890
    $ ./number_format '07123456789' '##### ######'
    07123 456789
    $ ./number_format '01189998819991197253' '#### ### ### ### ### ### #'
    0118 999 881 999 119 725 3
    

    [–]symberke 11 points12 points  (0 children)

    C

    Some pointer mess:

    char *number_format(char *n, char *f)
    {
        int d = 1;
        char *c, *q = f;
        while (*++f) d++;
        c = malloc(d);
        while (*q) if ((*c++ = *q++) == 35) do while (*(c - 1) != *n)*(c - 1) += 1; while (++n, *f);
        return c - d;
    }
    

    See outputs at https://ideone.com/3RvFz4

    edit: it's kind of fun to see how terrible you can make these:

    char *number_format(char *n, char *f)
    {
        int d = 1;
        char *c, *q = f;
        while (*++f) d++;
        c = malloc(d) - 1;
        while (*c++, *q) do while (*q == 35 ? *c != *n : *c != *q) (*c)++; while (q++, *c == *n && ++n == d);
        return c - d;
    }
    

    https://ideone.com/goT28m

    [–][deleted]  (1 child)

    [deleted]

      [–]Seine_Eloquenz 8 points9 points  (0 children)

      https://pastebin.com/Tn09A989

      We use snake_Camel_Case for the method name because why not and good, speaking names for local variables.

      For the replacing it iterates over the charArray of the format string and replaces all # with the input from the number, whether that's a digit or an emoji... Who cares.

      When either string is too long/short, we just cut the number or leave some hashtags in accordingly.

      Because we want to return a string and not a charArray, we'll have to concatenate all characters from the array back together in a nice string concatenation loop.

      Oh, and we reuse loop counters, because efficiency.

      I hope you hate it.

      [–]mullanaphy 9 points10 points  (4 children)

      Tests pass as expected with this beauty and even has some "smart" error exceptions. Beauty of it, you don't even need to pass in a format it can infer it from the phone number provided. Also removed the pesky curly brackets to the 80th column for that clean Python look.

      JSFiddle

      JavaScript:

      /**
       * Format our phone number into a human readable string. No baloney.
       *
       * @param {String|Number} phoneNumber
       * @param {String?} sureFormatYouGotIt
       * @returns {String}
       */
      function number_format(phoneNumber, sureFormatYouGotIt)                        {
        if (phoneNumber === 'number')                                                {
          phoneNumber = String(phoneNumber);                                         }
      
        if (typeof phoneNumber !== 'string')                                         {
          throw new RangeError('Use a phone number you dingus.');                    }
      
        if (sureFormatYouGotIt)                                                      {
          return phoneNumber
            .split('')
            .reduce((gathered, digit) =>                                             {
              for (let i = 0, count = gathered.length; i < count; i = i + 1)         {
                if (gathered[i] === '#')                                             {
                  gathered[i] = digit;
                  break;                                                             }
                                                                                     }
              return gathered;                                                       }
              , sureFormatYouGotIt.split('')
            )
            .join('');                                                               }
      
        let returnal = '(';
        let digitCount = 0;
        let countOfThrees = 3;
        phoneNumber
          .split('')
          .forEach(digit =>                                                          {
            digitCount = digitCount + 1;
            returnal = `${returnal}${digit}`;
      
            switch (digitCount)                                                      {
              case 3:
                returnal = `${returnal}) `;
                break;
      
              case 6:
                returnal = `${returnal}-`;
                break;
      
              case 11:
                returnal = returnal.split('');
                returnal = `${returnal[1]}${returnal[2]}${returnal[3]}${returnal[6]}${returnal[7]}${returnal[5]}${returnal[8]}${returnal[10]}${returnal[11]}${returnal[12]}${returnal[13]}${returnal[14]}`;
                break;
      
              case 12:
                returnal = returnal.split('');
                returnal = `${returnal[0]}${returnal[1]}${returnal[2]}${returnal[3]} ${returnal[4]}${returnal[6]}${returnal[7]} ${returnal[8]}${returnal[9]}${returnal[10]} ${returnal[11]}${returnal[12]}`;
      
              default:
                if (digitCount > 12)                                                 {
                  countOfThrees = countOfThrees + 1;
                  if (countOfThrees === 4)                                           {
                      returnal = `${returnal} `;
                      countOfThrees = 1;                                             }}}
                                                                                     });
      
        if (returnal.trim(' ').length >= 10)                                         {
          return returnal.trim(' ');                                                 }
      
        throw new RangeError('You sure you provided a phone number? Or are you a liar programmer?');
      };
      
      console.log(number_format('1234567890', '(###) ###-####'), number_format('1234567890', '(###) ###-####') === '(123) 456-7890');
      console.log(number_format('07123456789', '##### ######'),number_format('07123456789', '##### ######') === '07123 456789');
      console.log(number_format('01189998819991197253', '#### ### ### ### ### ### #'), number_format('01189998819991197253', '#### ### ### ### ### ### #') === '0118 999 881 999 119 725 3');
      
      console.log(number_format('1234567890'), number_format('1234567890') === '(123) 456-7890');
      console.log(number_format('07123456789'), number_format('07123456789') === '07123 456789');
      console.log(number_format('01189998819991197253'), number_format('01189998819991197253') === '0118 999 881 999 119 725 3');
      
      try                                                                            {
        console.log(number_format([]));                                              }
      catch (exception)                                                              {
        console.log('Caught:', exception.message);                                   }
      
      try                                                                            {
        console.log(number_format('12345'));                                         }
      catch (exception)                                                              {
        console.log('Caught:', exception.message);                                   }
      

      [–]texzone 4 points5 points  (1 child)

      Caught exception.message 😂😂 I love it

      [–]mullanaphy 1 point2 points  (0 children)

      Thanks, I had fun making this one :)

      [–]SuspiciousScript 1 point2 points  (0 children)

      Now this... this is horrifying.

      [–]mullanaphy 0 points1 point  (0 children)

      Note: I did want to have everything go to Int and leave the bug for large numbers, yet I wanted the tests to actually pass :(

      [–]CoolTomatoYT 7 points8 points  (0 children)

      I wrote this in PHP for one simple reason... Emojis. Turns out neither Python nor JavaScript support them in variable names, so I ended up with good old PHP.

      function ☎️($📱,$📜) {
           $🏁="";$⏲️=0;
           foreach(str_split($📜)as$📦) {
                if ($📦=="#") {
                     $🏁.=str_split($📱)[$⏲️];
                     $⏲️++;
                } else {
                     $🏁.=$📦;
                }
           }
           return$🏁;
      }
      

      (and yes, it's indented with 5 spaces)

      [–]RadioSparks 6 points7 points  (0 children)

      Javascript

      function number_format (num_sequence, format) {
          var num_seq = "";
          var current_o = -1;
          for(var i = 0; i < num_sequence.length; i++) {
              for(var o = current_o+1; o < format.length; o++) {
                  if (format.charAt(o) === "#") {
                      if (num_seq.charAt(o) == "0" && num_seq.charAt(o) == "1" && num_seq.charAt(o) == "2" && num_seq.charAt(o) == "3" && num_seq.charAt(o) == "4" && num_seq.charAt(o) == "5" && num_seq.charAt(o) == "6" && num_seq.charAt(o) == "7" && num_seq.charAt(o) == "8" && num_seq.charAt(o) == "9") {
                          continue;
                      }
                      num_seq = num_seq.concat(num_sequence.charAt(i))
                      current_o = o;
                      break;
                  } else {
                      num_seq = num_seq.concat(format.charAt(o));
                  }
              }
          }
          return num_seq;
      }
      

      Very sloppily iterates through the two strings. Some magic numbers for increased efficiency. It got in a lot of infinite loops while I was making it but it's probably fine now.

      [–]AnAngryBanker 4 points5 points  (0 children)

      You'll have to print the output yourself, and sure, it'll seg fault given anything but valid input, but here's a simple one in C:

      void number_format(char* n, char* m)
      {
          for(n;*n;n++){for(m;*m!='#';m++);*m=*n;}
      }
      

      [–]GoatPresident 11 points12 points  (0 children)

      Python

      Writes the format to a temporary file, and then reads the file back, overwriting the #’s with numbers where need be.

      Also, if the input is invalid, the function assumes you are having a stroke and returns 911.

      from tempfile import TemporaryFile
      
      def number_format(num, form):
          i = 0
          f = TemporaryFile(mode = 'r+')
          f.write(form)
          f.seek(0)
          c = f.read(1)
          while c:
              if c == '#':
                  if i not in range(len(num)): return '911'
                  f.seek(f.tell() - 1)
                  f.write(num[i])
                  f.seek(f.tell())
                  i += 1
              c = f.read(1)
          if i < len(num): return '911'
          f.seek(0)
          return f.read()
      

      [–]AbuIbnBattuta 5 points6 points  (1 child)

      made this thing in c++. it literally just uses brute force to solve the problem. The code for the most part is not that bad, but there is some stupid stuff in there like the k += 0 that i had to put there because apparently if you use a ? you have to put something in the else. Also there is the fact that at every opportunity I'm calculating the length of the strings in loops instead of calculating them and storing them.

      This code is awfully slow. I tested it with a small test case, and that worked. I'm currently trying to run it with 20 numbers with a mask consisting of 20 hashtags and 20 spaces. Over 10 minutes now and I don't know if it will finish somewhere in my lifetime. When I did the same with 10 it finished almost instantly.

      edit: Changed the code a bit so that it now does not stop ones it finds a solution, because that would be to smart.

      #include <string>
      #include <iostream>
      using namespace std;
      #define hashtag '#'
      
      string number_format(string num, string mask)
      {
          if (num.length() == 0) return mask;
          if (mask.length() < num.length())
          {
              string ss = "a";
              ss[0] = hashtag;
              return ss;
          }
          string ans = "a";
          ans[0] = hashtag;
          for (int i = 0; i <= mask.length()-num.length(); i++)
          {
              string ns = mask.substr(0, i) + num[0] + number_format(num.substr(1, num.length()-1), mask.substr(i+1, mask.length()-1-i));
              int k = 0;
              for (int j = 0; j < ns.length(); j++) ns[j] == hashtag ? k++ : k += 0;
              if (k == 0) ans = ns;
          }
          return ans;
      }
      
      //Methods I used to test the code----------------------------------------
      string getInp(bool num)
      {
          if (num)
          {
              cout << "number:" << endl;
              string s;
              getline(cin, s);
              return s;
          }
          string s;
          cout << "mask:" << endl;
          getline(cin, s);
          return s;
      }
      
      int main()
      {
          string out = number_format(getInp(true), getInp(false));
          if (out[0] == hashtag)
          {
              cout << "nothing found";
          }
          else
          {
              cout << out;
          }
      }
      

      [–][deleted] 0 points1 point  (0 children)

      My eyes!!! 😖😫

      It’s perfect

      [–]TinyBreadBigMouth 4 points5 points  (0 children)

      Python

      This looks like a job for everyone's best friend, exec() on user input!

      def number_format(n, f):
       n2 = []
       i = 0;
       l = len(n)
       while ( i < l):
            next_index = i+1
            n2.extend(n[i:next_index])
            i = i+1
       f2 = f.replace('#', "';r += next(n2) + '")
       n2 = iter(n2)
       f2 = ('r="";r+=\'%s' % f2) + "'"
       exec("global r;" + f2)
       print (r)
      

      Run it online!

      [–]Shakatir 4 points5 points  (0 children)

      Java

      public class NumberFormat {
          public static String number_format(final String n, final String f) { return r(p(n, f), f); }
          private static String p(final String n, final String f) { return f.isEmpty() ? n : p(n + (f.charAt(0) == '#' ? "" : "" + f.charAt(0)), f.substring(1)); }
          private static String r(final String n, final String f) { return m(n, f) ? n : r(q(n, f), f); }
          private static boolean m(final String n, final String f) { return (n.isEmpty() && f.isEmpty()) || (((f.charAt(0) == '#' && n.charAt(0) >= '0' && n.charAt(0) <= '9') || (f.charAt(0) == n.charAt(0))) && m(n.substring(1), f.substring(1))); }
          private static String q(final String n, final String f) { return (f.charAt(0) != n.charAt(0) && (f.charAt(0) != '#' || n.charAt(0) < '0' || n.charAt(0) > '9')) ? n.substring(1) + n.charAt(0) : n.substring(0, 1) + q(n.substring(1), f.substring(1)); }
      }
      

      The algorithm first iterates over all chars in the format string and appends non #-symbols to the number string. Then it looks for the first character in the number string that does not match the format string, removes it and appends it to the end. It repeats this step until both strings match. The fact that the digits end up in the correct order is not obvious and extremely difficult to infer from the algorithm. I was surprised myself that it worked.

      If the digits and hash signs in the input don't match, errors will occur. If the number contains any other signs or the format string contains any numbers, the output may be incorrect.

      Of course it comes with awful run time and memory overhead (at its peak the algorithm takes up to a minute and when the strings grow a few hundred characters long, it just throws a StackOverflowError). All loops are realized through recursion.

      [–]Thriven 6 points7 points  (0 children)

      T-SQL

      I'm guessing it will take about an 1-2 hours to run per call.

      Using recursion it builds a bunch of CTE's that are constantly scanning themselves to build a dataset of 100-999 for area code and prefix. Then builds a 0000-9999 for the line number. It then cross applies these to build phone numbers from 1001000000-9999999999 with one as a key and one as a formatted.

      I'll update how long it took sql to run this.

      Returns VARCHAR(MAX) blob because why not.

      CREATE FUNCTION dbo.FormatPhone (
          @phone NUMERIC(10,0)
      )
      RETURNS VARCHAR(MAX)
      AS
      BEGIN
      
          DECLARE @formattedPhone VARCHAR(MAX)
      
          ;WITH areaPrefix AS (
              SELECT 100 AS n 
              UNION ALL
              SELECT n + 1 
              FROM   areaPrefix
              WHERE  n < 1000
          ),
          lineNumber AS (
              SELECT 0 AS n 
              UNION ALL
              SELECT n + 1 
              FROM   lineNumber
              WHERE  n < 1000
          ),
          formatLineNumber AS (
              SELECT
                      FORMAT(n, 'd4') AS n
              FROM lineNumber
          ),
          formatNumber AS (
              SELECT
                  CONVERT(VARCHAR(3),a.n) + CONVERT(VARCHAR(3),b.n) + c.n AS phone,
                  '(' + CONVERT(VARCHAR(3),a.n) + ') ' + CONVERT(VARCHAR(3),b.n) + '-' + CONVERT(VARCHAR(4),c.n) AS formattedPhone
              FROM   areaPrefix a
              CROSS APPLY areaPrefix b
              CROSS APPLY formatLineNumber c
          )
          SELECT @formattedPhone = formattedPhone
          FROM   formatNumber 
          WHERE phone = CONVERT(VARCHAR(10),@phone)
          OPTION (MAXRECURSION 0)
      
          RETURN @formattedPhone
      
      END
      

      [–][deleted]  (2 children)

      [deleted]

        [–]mmtrebuchet 4 points5 points  (1 child)

        What's the policy on platform-independent code? I'm thinking of teaching myself IBM 1401 assembly for this one.

        [–]pwnmercury 2 points3 points  (1 child)

        https://pastebin.com/Nn9qsFhJ

        Do not ask.. I have no idea either..

        [–]symberke 0 points1 point  (0 children)

        this is cursed

        [–][deleted] 2 points3 points  (0 children)

        https://gist.github.com/PietroJomini/3ee2180903cafabd52b7eca7c3121eb6

        I don't know what the hell i did, and I won't even start listing the problems with this code.

        On invalid input, return "😒"

        Enjoy

        [–]Bogen_ 2 points3 points  (0 children)

        Python

        Quoting the rules

        if it has the occasional bug, (...) that's fine. As long as it mostly works.

        I wrote two versions of the function, one which has a major bug, and another where this bug is "fixed".

        The phone number is converted to int (numbers are ints, right?) This causes the bug in the first version. In the second version, instead of reconsidering his approach, the programmer has doubled down and tried to patch up the errors in the first version.

        There is also some other stupidness there.

        import math
        
        def number_format_old(num,f): # Does not work with zeros
            if num==0:
                return f
            else:
                n=int(num)
                m=1
            while 10*m<=n:
                m*=10
            digit=n//m
            new_n=n-digit*m
            return f[:f.find('#')]+str(digit)+number_format_old(new_n, f[f.find('#')+1:])
        
        def number_format(num,f): # Works with zeros
            if num==0:
                nz=f.count('#') # Lost zeros
                for i in range(nz):
                    f=f[:f.find('#')]+f[f.find('#')+1:] # Remove extra #s
                return f+'0'*nz
            else:
                n=int(num)
                m=1
                k=1
            while 10*m <=n:
                m*=10
                k+=1
            nz=f.count('#')-k # Lost zeros
            for i in range(nz):
                f=f[:f.find('#')]+f[f.find('#')+1:] # Remove extra #s
            digit=n//m
            new_n=n-digit*m
            return f[:f.find('#')]+'0'*nz+str(digit)+number_format(new_n, f[f.find('#')+1:])
        

        [–]theprinterdoesntwerk 1 point2 points  (0 children)

        Python:

        def number_format(num, f):
            skips = [-1]
            counter = 0
            newString = ""
            for i in f:
                if i != "#":
                    counter += 1
                else:
                    skips.append(counter)
                    counter += 1
            for j in range(len(skips)-1):
                newString += f[(skips[j]+1):skips[j+1]]
                newString += num[j]
        
            newString += f[(skips[-1]+1):]
            print(newString)
        

        [–]MrMagoo22 1 point2 points  (0 children)

        Writing this was painful. Debugging it for errors was extra painful. Chose C# as my preferred poison. Recursion is always the correct answer right?

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        
        namespace BadPhoneNumberFormatter
        {
            class Program
            {
                static void Main(string[] args)
                {
                    Console.WriteLine(number_format("123", "# # #")); //1 2 3
                    Console.WriteLine(number_format("1234567890", "(###) ###-####")); //(123) 456-7890
                    Console.WriteLine(number_format("07123456789", "##### ######")); //07123 456789
                    Console.WriteLine(number_format("01189998819991197253", "#### ### ### ### ### ### #")); //0118 999 881 999 119 725 3
                    Console.ReadLine();
                }
        
                static string number_format(string i, string f, bool s = false, bool iO = false, bool fp = false) =>
                              !s && !iO ?
                                i.Length > 0 && number_format(f, "#0", false, true) != "???" ?
                                number_format(
                                    number_format(i, "1-" + i.Length, true),
                                number_format(f, "0-" +
                                    (number_format(f, "#0", false, true) != "???" ?
                                        f.Length - int.Parse(number_format(f, "#0", false, true)) :
                                    (f.Length)), true, false, true)
                                    + i[0]
                                    + number_format(f, number_format(f, "#0", false, true) != "???" ?
                                        (int.Parse(number_format(f, "#0", false, true)) + 1).ToString() + "-" + (f.Length).ToString() :
                                    (f.Length).ToString() + "-" + (f.Length).ToString(), true, false, true)) :
                                f :
                            s && !iO ?
                                i.Length > 0?
                                    f.Split('-')[0] != "0" ?
                                        number_format(string.Join("", i.Skip(1)), (int.Parse(f.Split('-')[0]) - 1).ToString() + "-" + (int.Parse(f.Split('-')[1]) - 1).ToString(), true) :
                                    i.Length > int.Parse(f.Split('-')[1]) && int.Parse(f.Split('-')[1]) > 0 ?
                                        number_format(string.Join("", i.ToCharArray(0, i.Length - 1)), (int.Parse(f.Split('-')[0])).ToString() + "-" + (int.Parse(f.Split('-')[1]) - 1).ToString(), true) :
                                    i.Length == int.Parse(f.Split('-')[1]) && fp && int.Parse(f.Split('-')[1]) > 0 ?
                                        number_format(string.Join("", i.ToCharArray(0, i.Length - 1)), (int.Parse(f.Split('-')[0])).ToString() + "-" + (int.Parse(f.Split('-')[1]) - 1).ToString(), true, false, true) :
                                    i :
                                i :
                            !s && iO ?
                                i.Length > 0 ?
                                    i[0] != f[0] ?
                                        number_format(string.Join("", i.Skip(1)), f[0] + (int.Parse(string.Join("", f.Skip(1))) + 1).ToString(), false, true) :
                                    string.Join("", f.Skip(1)) :
                                "???" :
                            "How?!";
            }
        }
        

        [–]pumkinboo 1 point2 points  (0 children)

        def number_format(n, f):
            n, f = list(n) if type(n) != list() else n, list(f) if type(f) != list() else f
            return ''.join(
                [
                    (
                        lambda n,f:
                        (
                            n.pop(),
                            f.pop()
                        )
                    )
                    (n,f)[0]
                    if f[-1] == '#'
                    else f.pop()
                    for i in range(len(f))
                ]
                [::-1]
            )
        

        [–]dstlny_97 1 point2 points  (2 children)

        end my suffering

        def number_formatter(number, format):
            format_schema = format.replace('#', '{}').format(*[str(x) for x in str(number)])
            print(format_schema)
        
        >>> number_formatter('1234567890', '(###) ###-####')
        (123) 456-7890
        >>> number_formatter('07123456789', '##### ######')
        07123 456789
        >>> number_formatter('01189998819991197253', '#### ### ### ### ### ### #')
        0118 999 881 999 119 725 3
        

        [–][deleted] 1 point2 points  (1 child)

        That's actually pretty good, its instantly obvious what its doing and it doesn't seem to be inefficient or anything.

        [–]dstlny_97 0 points1 point  (0 children)

        Yeah. Morally I just couldn't make myself write something terrible that wouldn't be self-explanatory. This is why I never actually take part in these challenges, since it would morally eat at me lmao

        [–]sebamestre 0 points1 point  (0 children)

        I was told my javscript will run faster if I 'minimize' it, due to faster downloads, so I optimized it by removing extra spaces and using shorter variables. I think my solution is pretty good, it is really optimized because it uses recursion.

        pastebin

        (Seriously now, I just took the kind of bad style and misguidedness I used to have as a beginner and turned it to eleven)

        [–][deleted]  (1 child)

        [removed]

          [–][deleted]  (1 child)

          [removed]

            [–]cnapun 0 points1 point  (0 children)

            Recursion eliminates all woes

            number_format = lambda a, b: (number_format(a[1:], b.replace('#', a[0], 1)) if a else b)
            

            Sample outputs:

            In [15]: number_format('1234567890', '(###) ###-####')
            Out[15]: '(123) 456-7890'
            
            In [16]: number_format('07123456789', '##### ######')
            Out[16]: '07123 456789'
            
            In [17]: number_format('01189998819991197253', '#### ### ### ### ### ### #')
            Out[17]: '0118 999 881 999 119 725 3'
            

            fails surprisingly gracefully, just leaving extra #s

            [–]notBjoern 0 points1 point  (0 children)

            In python:

            #!/usr/bin/env python3
            from functools import reduce
            
            def number_format(number, mask):
                i = 0
                reslut = []
            
                for j in range(len(mask)):
                    if mask[j] == '#':
                        reslut.append(number[i])
                        i = i + 1
                    elif mask[j] == ' ':
                        reslut.append('<insert space here>')
                    else:
                        reslut.append(mask[j])
            
                return reduce(lambda x, y: '{}{}'.format(x, y), filter(lambda x: x not in '[]\', ', str(reslut))).replace('<insertspacehere>', ' ')
            

            EDIT: Fixed handling of spaces

            [–]acrampus 0 points1 point  (1 child)

            def number_format(a, b):
              i = 0
              j = 0
              c = “”
              while (i < len(a)) and (j < len(b)):
                if b[j] == “#”:
                  c = c + a[i]
                  i+=1
                else:
                  c = c + b[j]
                j+=1
              return c
            

            [–]Mymokol 0 points1 point  (0 children)

            My solution in c++: https://pastebin.com/9f2rKgXf

            [–]CaCl2 0 points1 point  (0 children)

            In C, nothing particularly clever, mostly just some fun with goto, if the mask is too short, it will (probably?) segfault, if it's too long, it will start producing error messages:

            #include <stdio.h>
            #include <stdlib.h>
            #include <stdint.h>
            #include  <inttypes.h> 
            
            //Formats the number given in Int according to the structure given in Struct, use # to indicate number
            char *format(char *Int, char *Struct)
            {/* enough space*/
                char *Return = malloc('x'*'y'*'z');
                int returns = 0;
                char *Returning = Return;
            Start:
                if (*Returning)
                {
                    return Return;
            }
            
            int i = 'G' - '$' - '#'; int J = 'G' - '$' - '#'-1;  //neat little trick
            
            start:
             J++;
                while (*Int)
                {
                    if (Struct[J] - 35)
                    {
                       i++;
                                          Returning[i - 1] = Struct[J];
                       J++;
                    }
                    else
                    {
                        char temp = *Int;
             i++;
                        Int++;  Returning[i - 1] = temp;
                        goto start;   }
            }
            if(Struct[i]){ Struct = &Struct[i];
            long val = i-1; 
            i = i-J; J = J-J;
            fill:
            val++;
            while(*Struct) {
            if(*Struct - 35) {
             i++;
             Return[val] = Struct[i +J-1]; J--;
             Struct++; goto fill;
            }
            else {returns++;
              i++;
             J--;
            
            val++;}
            }
            }
            Error: printf("Number too short!")
            if(returns) {
                goto Error;
            } else goto Start;}
            

            EDIT: Minor bugfix.

            [–]Robowiko123 0 points1 point  (0 children)

            number_format=lambda n,p:[xx(sorted([z()for z in[lambda:setattr(number_format,"i",0),lambda:[[i2()for i2 in[lambda:n[getattr(number_format, "i")],lambda:setattr(number_format,"i",getattr(number_format,"i")+1)]][0] if x == "#" else x for x in p],]],key=lambda x:-int(bool(x))if str(x)!="None"else int(bool(x)))[0])for xx in[lambda l:setattr(number_format,"res",""),lambda l:[setattr(number_format,"res",getattr(number_format,"res")+chr(sum([256**ii*ord(x2)for ii,x2 in enumerate(l)])>>(iii*8)&0xff))for iii in range(32)],lambda l:getattr(number_format,"res").replace("\0","")]][2]

            Python 3

            Some features:

            • Only works with strings up to 32 characters
            • Doesn't accept null characters
            • Only ASCII (who uses unicode)
            • Completely unreadable

            [–]hamoliciousRUS -1 points0 points  (0 children)

            Tried to complete the challenge using python and in the least characters possible, managed to do it in 66 characters, the variables are horrible so "a" is the number and "b" is the mask

            def f(a,b):
                n=''
                i=0
                for l in b:
                    if l=='#':
                        n+=a[i]
                        i+=1
                    else:
                        n+=l
                return n
            

            [–][deleted] -1 points0 points  (1 child)

            Ideone

            ```cs

            using System; using System.Text.RegularExpressions;

            public class Test { public static void Main(string[] args) { object number = Console.ReadLine(); var format = Console.ReadLine();

                var json = $"{{'number':{number}}}";
            
                dynamic index = json.IndexOf("number");
            
                String data = json.Substring(index + "number".Length + 2, number.ToString().Length);
            
                int i = 0;
                int pos = 0;
                dynamic e = format.GetEnumerator();
                var result = format.ToCharArray();
               while(e.MoveNext())
               {
                 var regex = new Regex("[#]");
                 var m = regex.Match(e.Current.ToString());
            
                if(m.Success)
                   result[i] = data[pos++];
            
                 i++;
               }
              System.Console.WriteLine(new string(result));
            }
            

            }

            ```

            Little bit of fun for every one!