DEV Community

Daily Challenge #40 - Counting Sheep

dev.to staff on August 14, 2019

You're having trouble falling asleep, so your challenge today is to count sheep! Given a non-negative integer, 3 for example, return a string wit...
Collapse
 
badrecordlength profile image
Henry 👨‍💻 •

This was quite a simple one so I decided to spice it up with emoji! Also, next-gen sleep simulation at the end.

Code:

# -*- coding: UTF-8 -*-

def countSheep(sheepToCount):
        sheepString = ""
        outputString = ""
        for i in range(sheepToCount):
                sheepString += "🐑 "
                outputString += "{}... ".format(sheepString)
        outputString +="ZZZzzzzzzz"
        print(outputString)

countSheep(5)

Output:

🐑 ... 🐑 🐑 ... 🐑 🐑 🐑 ... 🐑 🐑 🐑 🐑 ... 🐑 🐑 🐑 🐑 🐑 ... ZZZzzzzzzz
Collapse
 
ynndvn profile image
La blatte •

Did anybody talk about oneliner?

f=(i)=>[...Array(i)].map((_,i)=>`${i+1} sheep... `).join``

And the results

f(10);
// "1 sheep... 2 sheep... 3 sheep... 4 sheep... 5 sheep... 6 sheep... 7 sheep... 8 sheep... 9 sheep... 10 sheep... "
Collapse
 
andymardell profile image
Andy Mardell • • Edited

This is sweet. Something similar but with more Array and less map:

const f = i => Array.from(Array(i), (_, i) => `${i + 1} sheep... `).join``

or

const f = i => Array.from({ length: i }, (_, i) => `${i + 1} sheep... `).join``
Collapse
 
alvaromontoro profile image
Alvaro Montoro •

Scheme

(define (countSheep n)
  (if (< n 1) 
    ""
    (string-append (countSheep (- n 1)) (number->string n) " sheep...")
  )
)

A demo can be seen in Repl.it. The function would be called (countSheep 4) and the result would be:

"1 sheep...2 sheep...3 sheep...4 sheep..."

Collapse
 
itsdarrylnorris profile image
Darryl Norris •

PHP

<?php

/**
 * Daily Challenge #40 - Counting Sheep
 *
 * @param  int    $number Number of sheeps.
 * @return string
 */
function countingSheep(int $number): string
{
  $text = '';
  for ($i = 1; $i <= $number; $i++) {
    $text .= "$i sheep...";
  }

  return $text;
}


echo countingSheep(3);
// Output: 1 sheep...2 sheep...3 sheep...
Collapse
 
itsdarrylnorris profile image
Darryl Norris • • Edited

JavaScript

/**
 * Daily Challenge #40 - Counting Sheep
 *
 * @param  {number}        Number of sheeps.
 * @return {string}
 */
const countingSheep = number => {
  // Checking if positive integer or not.
  if (!(number >>> 0 === parseFloat(number))) {
    return `${number} is not a positive integer`;
  }

  let text = '';

  // Building text.
  for (let i = 1; i <= number; i++) {
    text += `${i} sheep...`;
  }
  return text;
};

console.log(countingSheep(3));
// Output: 1 sheep...2 sheep...3 sheep...

Collapse
 
danielsclet profile image
Daniel Santos •

JavaScript

function cs(n) {
    if (typeof n != "number" && n < 0) return `${n} is not a valid number`;

    let text = "";

    for(let x = 0; x < n; x++) {
        text += `${x} sheep... `
    }

    return text;
}

cs(3) // 0 sheep... 1 sheep... 2 sheep...
Collapse
 
dak425 profile image
Donald Feury •

PHP

I counted bugs because that is more reflective of what I would do while working :)

I also added a message for if you are able to go to sleep immediately

<?php

function countBugs(int $bugs): string {
  if ($bugs === 0) {
    return "sleep tight..." . PHP_EOL;
  }

  $count = 0;
  $text = ++$count . " bug..." . PHP_EOL;

  while ($count < $bugs) {
    $text .= ++$count . " bugs.." . PHP_EOL;
  }

  return $text;
}

echo "Counting three bugs..." . PHP_EOL;
echo countBugs(3);

echo "Counting no bugs..." . PHP_EOL;
echo countBugs(0);
Collapse
 
hanachin profile image
Seiei Miyagi •

ruby <3

def count_sheep(n)
  1..n |> map { "#@1 sheep..." } |> join
end
Collapse
 
thepeoplesbourgeois profile image
Josh •

Ruby has pipes now?

Collapse
 
hanachin profile image
Seiei Miyagi •

Yes! pipeline operator added.

Feature #15799: pipeline operator - Ruby master - Ruby Issue Tracking System

And Numbered parameters.

Feature #4475: default variable name for parameter - Ruby master - Ruby Issue Tracking System

It's not released yet. You can try those new syntax by rbenv install 2.7.0-dev.

Collapse
 
hanachin profile image
Seiei Miyagi •

Sadly, pipeline operator is reverted.
github.com/ruby/ruby/commit/2ed68d...

Collapse
 
kvharish profile image
K.V.Harish •

My solution in js

const murmur = (times) => Array(times).fill()
                                      .map((value, index) => `${index+1} sheep...`)
                                      .join(' ');
Collapse
 
peter279k profile image
peter279k •

Here is the simple solution with PHP:

function countsheep($num){
  $sheepString = "";

  for ($index=1; $index<=$num; $index++) {
    $sheepString .= (string)$index . " sheep...";
  }

  return $sheepString;
}
Collapse
 
thepeoplesbourgeois profile image
Josh • • Edited
shep = fn n -> 1..n |> Stream.map(&("#{&1} sheep")) |> Enum.join("...") end

IO.puts(shep.(5))
# 1 sheep...2 sheep...3 sheep...4 sheep...5 sheep

⬆️elixir
That was fast... might as well do it in another language too.
⬇️javascript

const shep = (n) => new Array(n).fill(null).map((_, i) => `${i+1} sheep`).join("...")

console.log(shep(5))
// 1 sheep...2 sheep...3 sheep...4 sheep...5 sheep
Collapse
 
jay profile image
Jay • • Edited

Rust solution: [Playground](

fn count_sheeps(num: u32) -> String {
    let sheep = "🐑"; 
    (1..=num)
        // .map(|n| format!("{} sheep...", n))
        .map(|n| format!("{}... ", sheep.repeat(n as usize)))
        .collect::<Vec<String>>()
        .join("")
}

// -> 🐑... 🐑🐑... 🐑🐑🐑... 
Collapse
 
bhaveshg profile image
BHAVESH GUPTA •

Most of the solutions are not taking input
0
into consideration.
Like for 0 the output should be
"0"
not an empty string.

Edit that can be made to question statement.
As according to question input can be a non-negative number. For rest of the inputs it should be like for 3,
"0 1 sheep...2 sheep... 3sheep..."

Pattern is print the numbers upto n starting with 0 and concate the string " sheep..." with them.

Collapse
 
alvaromontoro profile image
Alvaro Montoro •

I kind of understand your suggestion (as zero is not positive nor negative, and the question statement would be more accurate if it was "Given a positive integer"), but I don't see why you suggest that base case.

Why for zero the output should be "0" and not "0 sheep..." or an empty string?

Collapse
 
bhaveshg profile image
BHAVESH GUPTA •

I made some assumptions for the pattern.

As i think the pattern is to print the numbers upto inputted number and concatinating string " sheep...", so as the total number of string " sheep..." in output string is equal to inputted number. that is no string for 0 but the "0" represent the number.

Collapse
 
thepeoplesbourgeois profile image
Josh • • Edited

Oh, alright.

shep = fn
  0 -> ""
  n -> 1..n |> Stream.map(&("#{&1} sheep")) |> Enum.join("...") 
end

IO.puts(shep.(0))
# 
Collapse
 
konaarctic profile image
Kona Arctic • • Edited
#!/bin/bash
i=0
while [ $((++i)) -le $1 ] ; do
    echo $i sheep ...
done
Collapse
 
savagepixie profile image
SavagePixie •

Some recursivity in JavaScript

function countSheep(n) {
   while (n > 0) return countSheep(n - 1) + n + " sheep..."
}

or something like that.

Collapse
 
hectorpascual profile image

Python :

def count_sheep(n):
    for i in range(1,n+1):
        print(f"{i} sheep...", end=' ')

In one line :

count_sheep = lambda n : print(''.join([f"{i} sheep... " for i in range(1,n+1)]))
Collapse
 
jamespotz profile image
James Robert Rooke •

My solution in ruby

Collapse
 
thepeoplesbourgeois profile image
Josh •

What about a range?

Collapse
 
jamespotz profile image
James Robert Rooke •

Oh, yeah.

(1..num)

Forgot about range.

Collapse
 
jeddevs profile image
Theo •

Nice!
Trusty repl.it
Had no idea you could embed that,
how do you do that if you don't mind my asking?

Collapse
 
jamespotz profile image
James Robert Rooke •

Basically, you should add your '@username/replit_name' inside

{% replit [here] %}

See dev.to/p/editor_guide for more options.

Collapse
 
mangelsnc profile image
Miguel Ángel Sánchez Chordi •

PHP

 <?php

 $totalSheeps = abs(intval($argv[1]));

 for ($i = 1; $i <= $totalSheeps; $i++) {
     echo "$i sheeps...";
 }

 echo PHP_EOL;
Collapse
 
matrossuch profile image
Mat-R-Such •

Python

def count_sheep(n):
    return ''.join(map(lambda n: '%d sheep...' %(n),range(1,n+1)))
Collapse
 
choroba profile image
E. Choroba •

Perl solution, the integer is specified as an argument to the program:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

say map "$_ sheep...", 1 .. shift;
Collapse
 
tolgahanuzun profile image
Tolgahan ÜZÜN • • Edited

Welcome to my fantasy world. :D

n = 5

''.join(list(map(lambda x: f'{x+1} sheep... ', range(n))))

Output:

1 sheep... 2 sheep... 3 sheep... 4 sheep... 5 sheep... 
Collapse
 
oscherler profile image
Olivier “Ölbaum” Scherler •

Erlang:

% erl
1> Sheep = fun(N) -> lists:flatmap(fun(X) -> lists:concat([X, " sheep..."]) end, lists:seq(1, N)) end.
#Fun<erl_eval.7.91303403>
2> Sheep(3).
"1 sheep...2 sheep...3 sheep..."
Collapse
 
devparkk profile image
Dev Prakash •