DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #238 - One is the Loneliest Number

The range of vision of a digit is equal to its own value. 1 can see one digit to the left and one digit to the right, 2 can see two digits, and so on.

Thus, the loneliness of a digit is the sum of the digits which it can see.

Given a non-negative integer, your function must determine the loneliest number in the string.

Example

number = 34315
digit   can see on the left     can see on the right    loneliness
3         -                     4, 3, 1            4 + 3 + 1 = 8
4         3                     3, 1, 5            3 + 3 + 1 + 5 = 12
3         3, 4                  1, 5                   3 + 4 + 1 + 5 = 13
1         3                       5                3 + 5 = 8
5        3431                    -                 3 + 4 + 3 + 1 = 11

1 is the loneliest number, since it has the least friends and the lowest score.

Tests

lonelyNum(23456)
lonelyNum(42435)

Good luck!


This challenge comes from albertogcmr 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!

Top comments (5)

Collapse
 
vidit1999 profile image
Vidit Sarkar

Here is a Python solution,


def lonelyNum(number : int) -> int:
    digits = list(map(int, str(number)))
    loneliest = digits[0]
    min_loneliness = min_friends = float('inf')

    for i in range(len(digits)):
        left_friends = digits[max(0,i-digits[i]):i]
        right_friends = digits[i+1:min(len(digits),i+1+digits[i])]

        loneliness = sum(left_friends+right_friends)
        friend_count = len(left_friends+right_friends)

        if(loneliness < min_loneliness):
            loneliest = digits[i]
            min_loneliness = loneliness
            min_friends = friend_count
        elif(loneliness == min_loneliness and friend_count < min_friends):
            loneliest = digits[i]
            min_friends = friend_count

    return loneliest

Outputs,

print(lonelyNum(34315)) # output -> 1
print(lonelyNum(23456)) # output -> 2
print(lonelyNum(42435)) # output -> 2
Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli • Edited
function numToArray(num)
{
  let result = [];
  let n = num;
  while(Math.log10(n) > 0)
  {
    let i = n % 10;
    result.unshift(i)
    n = Math.floor(n / 10);
  }
  return result;
}

function lonliest(num)
{
  let parts = numToArray(num);
  let min = Number.MAX_SAFE_INTEGER;
  let minFriends = Number.MAX_SAFE_INTEGER;
  let minNum = Number.MAX_SAFE_INTEGER;
  let scores = parts.map((n, i, arr) => 
    {
      let lstart = n >= i ? 0 : i - n;
      let leftArr = arr.slice(lstart, i);
      let left = leftArr.reduce((acc, v) => acc + v, 0);
      let rightArr = arr.slice(i+1, i+n+1);
      let right = rightArr.reduce((acc, v) => acc + v, 0);
      let friendCount = leftArr.length + rightArr.length
      let score = left+right;
      if(score < min)
      {
        min = score;
        minNum = n;
        minFriends = friendCount;
      }
      else if(min == score) 
      {
        if(minFriends > friendCount)
        {
          minFriends = friendCount;
          minNum = n;
        }
      }      
      return score;
    });

  console.log(scores);

  return minNum;
}
Collapse
 
matteocacciola profile image
matteocacciola • Edited

Javascript:

function loneliest(number) {
    const digits = number.toString().split('').map((d) => +d);
    if (digits.indexOf(1) === -1) {
        return false;
    }

    const len = digits.length;
    let scores = new Array(len);
    digits.forEach(function (d, i) {
        let sum = 0;
        for (let j = Math.max(0, i - d); j < Math.min(i + d + 1, len); j++) {
            if (j !== i) sum += digits[j];
            scores[i] = sum;
        }
    });
    const minScore = Math.min(...scores);
    const iMinScore = scores.map((s, i) => {
        if (s === minScore) return i;
    });
    const minDigits = digits.filter((d, i) => iMinScore.filter(Number).includes(i));

    return Math.min(...minDigits);
}

console.log(23456, isOneWithLowestVision(23456));
console.log(42435, isOneWithLowestVision(42435));
console.log(34315, isOneWithLowestVision(34315));
console.log(212, isOneWithLowestVision(212));

Enter fullscreen mode Exit fullscreen mode
Collapse
 
redet_ profile image
redet • Edited
function lonelyNum(nu){     
    let num = nu.toString().split('').map((e)=>+e);
    let loneliest  = num[0];
    let loneliest_sum = Infinity;
    num.forEach(function(e,i){
        var sum = 0;// 52667776
        for(var j=Math.max(0,i-e);j<Math.min(i+e+1,num.length);j++)
            if(j!=i)
                sum+=num[j];


        if(loneliest_sum>sum && e < loneliest){
            loneliest = e;
            loneliest_sum = sum;
        }
    });
    return loneliest;
}

console.log(lonelyNum(34315)); // 1
console.log(lonelyNum(23456)); // 2
console.log(lonelyNum(42435)); // 2
Collapse
 
valperignon profile image
Valentin • Edited

That's my C solution :

code