Tagged: coding

Task 1: Beautiful strings

When John was a little kid he didn’t have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could… he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.

Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it.

The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn’t care about whether letters are uppercase or lowercase, so that doesn’t affect the beauty of a letter. (Uppercase ‘F’ is exactly as beautiful as lowercase ‘f’, for example.)

You’re a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?

Input
The input file consists of a single integer m followed by m lines.

Output
Your output should consist of, for each test case, a line containing the string “Case #x: y” where x is the case number (with 1 being the first case in the input file, 2 being the second, etc.) and y is the maximum beauty for that test case.

Constraints
5 ≤ m ≤ 50
2 ≤ length of s ≤ 500

My solution for this problem was fairly straight forward. Not the fastest solution I guess, but it works: get the string, count the unique alpha characters in it and add up the “beauty”

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<?php

$content=file_get_contents("input.txt");

$content=preg_replace("/\r\n/i","\n",$content);

$rows=explode("\n",$content);

$row_count=$rows[0];

if(!is_numeric($row_count)){

print("invalid input\n");

exit();

}

$handle=fopen("output.txt","w+");

for($case=1;$case<=$row_count;$case++){

$row=$rows[$case];

$row=strtolower(preg_replace("/[^a-zA-Z]/i","",$row));

if(!strlen($row)){

print("Case #$case: 0\n");

fwrite($handle,"Case #$case: 0\n");

continue;

}

$letters=array();

for($j=0;$j<strlen($row);$j++){

if(!isset($letters[$row[$j]])){

$letters[$row[$j]]=1;

}else{

$letters[$row[$j]]++;

}

}

$total_beauty=0;

$current_beauty=26;

arsort($letters);

foreach($lettersas$letter=>$count){

$total_beauty+=$count*$current_beauty;

$current_beauty--;

}

print("Case #$case: $total_beauty\n");

fwrite($handle,"Case #$case: $total_beauty\n");

}

Task 2: Balanced Smileys

Your friend John uses a lot of emoticons when you talk to him on Messenger. In addition to being a person who likes to express himself through emoticons, he hates unbalanced parenthesis so much that it makes him go

Sometimes he puts emoticons within parentheses, and you find it hard to tell if a parenthesis really is a parenthesis or part of an emoticon.

A message has balanced parentheses if it consists of one of the following:
– An empty string “”
– One or more of the following characters: ‘a’ to ‘z’, ‘ ‘ (a space) or ‘:’ (a colon)
– An open parenthesis ‘(‘, followed by a message with balanced parentheses, followed by a close parenthesis ‘)’.
– A message with balanced parentheses followed by another message with balanced parentheses.
– A smiley face “:)” or a frowny face “:(”

Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.
Input

The first line of the input contains a number T (1 ≤ T ≤ 50), the number of test cases.
The following T lines each contain a message of length s that you got from John.
Output

For each of the test cases numbered in order from 1 to T, output “Case #i: ” followed by a string stating whether or not it is possible that the message had balanced parentheses. If it is, the string should be “YES”, else it should be “NO” (all quotes for clarity only)
Constraints
1 ≤ length of s ≤ 100

I spent quite a lot of time, about 40 minutes on this one. I ended up with a recursive function which relies on a regular expression: “/(\(.*)(:\))?(:\()?(\))/U”. This regex will match the parts of the string which are in brackets even if the parts are containing a smiley. Then it is just a loop for counting the opening and closing parentheses.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

<?php

$content=file_get_contents("input.txt");

$content=preg_replace("/\r\n/i","\n",$content);

$rows=explode("\n",$content);

$row_count=$rows[0];

if(!is_numeric($row_count)){

print("invalid input\n");

exit();

}

functionreplace_once($haystack,$needle,$replacement){

$pos=strpos($haystack,$needle);

if($pos!==false){

returnsubstr_replace($haystack,$replacement,$pos,strlen($needle));

}else{

return$haystack;

}

}

functionis_balanced($string){

preg_match_all("/(\(.*)(:\))?(:\()?(\))/U",$string,$matches);

if(count($matches)&&count($matches[0])){

$remaining=$string;

foreach($matches[0]as$key=>$val){

$balanced=true;

$remaining=replace_once($remaining,$val,"");

$val=substr($val,1,strlen($val)-2);

$balanced=is_balanced($val);

if(!$balanced){

returnfalse;

}

}

returnis_balanced($remaining);

}else{

$string=str_replace(array(":)",":("),array("",""),$string);

$open=0;

for($i=0;$i<strlen($string);$i++){

if($string[$i]==")"){

if($open>0){

$open--;

}else{

returnfalse;

}

}

if($string[$i]=="("){

$open++;

}

}

if($open==0){

returntrue;

}else{

returnfalse;

}

}

}

$handle=fopen("output.txt","w+");

for($case=1;$case<=$row_count;$case++){

$row=$rows[$case];

if(is_balanced($row)){

print("Case #$case: YES\n");

fwrite($handle,"Case #$case: YES\n");

}else{

print("Case #$case: NO\n");

fwrite($handle,"Case #$case: NO\n");

}

}

fclose($handle);

Task 3: Find the min

After sending smileys, John decided to play with arrays. Did you know that hackers enjoy playing with arrays? John has a zero-based index array, m, which contains n non-negative integers. However, only the first k values of the array are known to him, and he wants to figure out the rest.

John knows the following: for each index i, where k <= i < n, m[i] is the minimum non-negative integer which is *not* contained in the previous *k* values of m.
For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1.
John is very busy making the world more open and connected, as such, he doesn't have time to figure out the rest of the array. It is your task to help him.
Given the first k values of m, calculate the nth value of this array. (i.e. m[n - 1]).
Because the values of n and k can be very large, we use a pseudo-random number generator to calculate the first k values of m. Given positive integers a, b, c and r, the known values of m can be calculated as follows:
m[0] = a
m[i] = (b * m[i - 1] + c) % r, 0 < i < k
Input
The first line contains an integer T (T <= 20), the number of test cases.
This is followed by T test cases, consisting of 2 lines each.
The first line of each test case contains 2 space separated integers, n, k (1 <= k <= 10^5, k < n <= 10^9).
The second line of each test case contains 4 space separated integers a, b, c, r (0 <= a, b, c <= 10^9, 1 <= r <= 10^9).
Output
For each test case, output a single line containing the case number and the nth element of m.

Well, I failed this task. Not because my solution wasn’t working. It wasn’t fast enough in some cases. I considered seed (it is not my first time on the Hacker cup) and tested it with large arrays but I missed a case when my script fails. The key speed up was when I realized that the analyzed array slices are repeating. They are repeating after every Kth element, therefor:

PHP

1

2

3

if($n>$k*2){

$n=$k+($n%$k)-1;

}

It gave me a huge speed up, but apparently not enough. I tried to run my script with the test cases provided by Facebook’s system and it didn’t finish in the 6 minutes limit even on the high-compute Amazon EC2 instances. Epic fail. Well next time. Anyway, my solution for task #3:

Every documentation and every code piece you can find about PHP’s header(“location: ….”); function recommends using die(); after the statement, but I never realized why until a couple of days ago. Most of the times I use die(); or exit(); after redirect statements, but for some reason I forgot to do so in one of my script. I learned the hard way why is it important: someone gained partial access to my site’s admin area. Turns out you can turn off redirects in your browser and in that case the rest of the script will execute without problems. Rookie mistake, I know, but I thought it’s worth sharing

register_shutdown_function
Recently I was building a PHP based load balancer for handling long running (video streams, sometimes up to 1 hour) processes. My biggest problem were if the user closed the page the load balancer had to react. This handy function is the best solution for the problem. Basically it calls the callback function when the script’s execution finishes or the user closes the browser window

scandir
If you are tired of using opendir, readdir and closedir, this function is for you

glob
Even better than scandir. It will only list the files matching the pattern passed in as an argument

CURLOPT_PROGRESSFUNCTION
This is a fairly new feature of the curl library. You can specify a callback function which will be executed every time a chunk of data comes back from the remote host. Usually I’m using it to create progress bars for long running curl processes

escapeshellcmd
I’m dealing with loads of user generated files in many different languages. As you may know the golden rule: “Users are idiots” so they put spaces, quotes and many many random characters in the file names. escapeshellcmd is a really handy function to escape a command before you call exec