DEV Community

Eduardo Carísio
Eduardo Carísio

Posted on

Knowledge test

I did a knowledge test where I received a link with 3 steps, unfortunately, I stayed stucked at second step.

The first step ask for to get te middle char of any word.
If the word has a even length, return 2 middle digits otherwise, the middle digit.

Solution

public static string GetMiddle(string s)
{
  if(s.Length <= 2) return s;

  var isEven = s.Length % 2 == 0;

  // I remove 1 digit because de array is 0 index;
  // I always round up for de odd words, even words the division is exact
  // rounding up odd words, i dont need to handle with even/odd on the 1 subtraction
  var middleDigit = (int)Math.Ceiling(s.Length * 1M / 2M) - 1;

  return s.Substring(middleDigit, isEven ? 2 : 1);
}
Enter fullscreen mode Exit fullscreen mode

At this point, everything is ok.


The second step asked to me for count the notes of an ATM dispenser just with notes of values: 100, 50 and 20.

Withdrawals

  • $260
  • $40
  • $230
  • $250

Outputs

  • {2, 0, 3}
  • {0, 0, 2}
  • {1, 1, 4}
  • {2, 1, 0}

Solution

public static int[] Withdraw(int amount)
{
  var result = new int[] { 0,0,0 };

  var note100Result = (int)Math.Floor(amount * 1M / 100M);

  if(note100Result > 0)
  {
    var remainValue = amount - (note100Result * 100);

    if(remainValue % 50 !=0)
      if(remainValue % 20 !=0)
        note100Result--;

    result[0] = note100Result;

    if(note100Result > 0)
      amount -= note100Result * 100;
  }

  var note50Result = (int)Math.Floor(amount * 1M / 50M);

  if(note50Result > 0)
  {
    var remainValue = amount - (note50Result * 50);

    if(remainValue % 20 !=0)
      note50Result--;

    result[1] = note50Result;

    if(note50Result > 0)
      amount -= note50Result * 50;
  }

  var note20Result = (int)Math.Floor(amount * 1M / 20M);

  if(note20Result > 0)
  {
    result[2] = note20Result;
  }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

The logic is: you just can proceed to another note if the remaining value is fully divisible for ANY ONE of the other notes, otherwise,
you need to subtract 1 note of the current note counter.

Of course, this can be done in other ways, with a loop and Linq as example, but I preferred to do like this to be more explainable.


As I didn't finish the second step, I even couldn't see the third step :(


As I said earlier, I stayed stucked at this step. I did this test after a long day of work, so my brain was not okay to do tasks like this.

My tip for this tests:

  • Do this in a unstressed moment, after take a snap or a good sleep night (if you can choice this moments obviously)

Top comments (0)