DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #201 - Complete the Pattern

Implement a function pattern, which returns the following pattern for up to n number of rows. If n < 1 then it should return " " i.e. empty string. There are no whitespaces in the pattern.

Pattern:
1
22
333
....
.....
nnnnnn

Examples

pattern(5):
1
22
333
4444
55555

pattern(11):
1
22
333
4444
55555
666666
7777777
88888888
999999999
10101010101010101010
1111111111111111111111

Tests

pattern(4)
pattern(8)
pattern(0.5)

Good luck!


This challenge comes from curious_db97 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Oldest comments (16)

Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell

import Data.List (intercalate)

pattern :: Int -> String
pattern n = intercalate "\n" $ map concat $ take n rows
  where rows = [ map show $ replicate i i | i <- [1..] ]
Collapse
 
jackfly26 profile image
JackFly26

You could use unlines instead of intercalate "\n" to join the lines. Also, it looks like you have to support decimals.

Collapse
 
exts profile image
Lamonte

Dart, didn't bother to deal with the float and use dynamic

void pattern(int n) {
  if(n < 1) {
    print(" ");
  }
  for(var x = 1; x < n+1; x++) {
    print(x.toString() * x);
  }
}

pattern(4);
pattern(8);
// pattern(0.5); // fails, not an int lol

// 1
// 22
// 333
// 4444
// 1
// 22
// 333
// 4444
// 55555
// 666666
// 7777777
// 88888888
Collapse
 
vidit1999 profile image
Vidit Sarkar

I think there is no new-line at the end.
Here is C++ solution:

string pattern(int number){
    string pat = "";

    // there is no new-line at the end so loop end is number-1
    for(int i=1;i<=number-1;i++){
        for(int j=0;j<i;j++)
            pat += to_string(i); // add the string version of number
        pat += "\n"; // add a new-line after adding the numbers each time 
    }

    // add the case of number at the end with no new-line
    for(int i=0;i<number;i++)
        pat += to_string(number);

    return pat;
}
Collapse
 
vidit1999 profile image
Vidit Sarkar • Edited

Python one liner :

pattern = lambda number : '\n'.join([str(i)*i for i in range(1,int(number)+1)])
Collapse
 
ynndvn profile image
La blatte • Edited

Well, here we go for some JS oneliner:

p=i=>[...Array(0|i)].reduce((a,_,l)=>[...a,Array(l+1).fill(l+1).join``],[]).join`\n`

It works like this :

  • First, build an array with a 0|i length (it will floor the number)
  • Use the reduce method to loop through the built array. Use the a parameter, which is the response array (initialized as [] and updated at each iteration), and the l parameter which is the current index.
  • For each iteration, add to the a array an item which is described as follow : Build a l+1-long array, fill it with l+1 (hence, if we are at l=1, the built item will be equal to [2, 2]). Then, use the join method to convert it to a string ('22'in this case)
  • Finally, once the array is built, use the join method one last time to add line breaks between lines
Collapse
 
itsjesusurias profile image
Jesus Urias

Here is my solution with Elixir

defmodule Meh do
  def pattern(number) when number < 1, do: " "
  def pattern(number) do
    Enum.map(1..number, fn x -> IO.puts(String.duplicate(Integer.to_string(x), x)) end)
  end
end

here is the output:

iex(1)> Meh.pattern(6)
1
22
333
4444
55555
666666
[:ok, :ok, :ok, :ok, :ok, :ok]
Collapse
 
lfrigodesouza profile image
Lucas Frigo de Souza

C#

    class Program
    {
        static void Main(string[] args)
        {
            Pattern(5);
            Pattern(11);
            Pattern(4);
            Pattern(8);
            Pattern(0.5);
        }

        public static void Pattern(double number)
        {
            for (var i = 1; i <= number; i++)
            {
                var str = string.Empty;
                for (var j = 0; j < i; j++)
                {
                    str += i;
                }
                Console.WriteLine(str);
            }
        }
    }

//1
//22
//333
//4444
//55555
//1
//22
//333
//4444
//55555
//666666
//7777777
//88888888
//999999999
//10101010101010101010
//1111111111111111111111
//1
//22
//333
//4444
//1
//22
//333
//4444
//55555
//666666
//7777777
//88888888
//
Collapse
 
amit_savani profile image
Amit Patel

Shortest snippet among all! That's why I ❤️ Ruby.

Collapse
 
julianengel profile image
Julian Engel

Python ... slightly more verbose :)

def pattern(n):

pat = ''
if n < 1:
    return pat
else:
    for index,value in enumerate(range(n),start=1):
        if value:
            pat += '\n'
        for i in range(index):
            pat += str(index)
    return pat
Collapse
 
avalander profile image
Avalander

Haskell

pattern :: Int -> String
pattern n
  | n > 0     = unlines [repeatNum x | x <- [1..n]]
  | otherwise = ""
  where
    repeatNum x = foldl (++) "" $ take x $ repeat $ show x

Output:

pattern 4
{-
1
22
333
4444
-}

pattern 8
{-
1
22
333
4444
55555
666666
7777777
88888888
-}

pattern 0.5
-- Compiler error, ha ha.
Collapse
 
ganesh profile image
Ganesh Raja

Python one-line solution

[print(str(i)*i) for i in range(1,n+1)]
Collapse
 
shhdharmen profile image
Dharmen Shah • Edited

JavaScript

function pattern(len) {
  if(isNaN(len) || len <1 ) {
    console.log('');
    return;
  }
  console.log( Array.from({ length: len }).map((item, index)=>{
    return Array.from({ length: index+1 }).fill(index+1).join('');
  }).join('\n'));
}
Collapse
 
maskedman99 profile image
Rohit Prasad

Python

var = float(input("Enter the number: "))

def pattern(var):
        if var < 1:
                print("")
        else:
                var = int(var)
                for i in range(var+1):
                        for j in range(i):
                                print(i,end = '')
                        print('\n',end='')

pattern(var)
Collapse
 
kesprit profile image
kesprit

My Swift solution :

func pattern(number: Double) -> String {
    guard number > 1 else { return " " }
    let numbers = (1...Int(number.rounded())).reduce(into: []) { $0.append($1) }
    return numbers.reduce(into: "") { $0.append("\(String.init(repeating: "\($1)", count: $1))\n") }
}

swift

Collapse
 
necrotechno profile image
NecroTechno

Rust :)

Playground link

fn pattern(input: f32) -> String {
    if input < 1.0 {
        return "".to_string();
    }
    let input_u32 = input.round() as u32;
    let mut response: String = "".to_string();
    for a in 0..input_u32 + 1 {
        for _b in 0..a {
            response.push_str(&a.to_string());
        }
        response.push_str("\n")
    }
    response
}

fn main() {
    println!("{}", pattern(4_f32));
    println!("{}", pattern(8_f32));
    println!("{}", pattern(0.5));
    println!("{}", pattern(2.5));
}