https://www.chess.com/live/game/3525260734

Statistics: Posted by dendiz — Mon Mar 11, 2019 8:03 am

]]>

Statistics: Posted by dendiz — Sat Feb 23, 2019 8:23 am

]]>

A different type of smothered mate

Statistics: Posted by dendiz — Tue Feb 19, 2019 5:48 am

]]>

CODE:

`public class SolrQueries { Map<String, String> charMap = new HashMap<>(); public SolrQueries() { charMap.put("o", "ö"); charMap.put("u", "ü"); charMap.put("c", "ç"); charMap.put("g", "ğ"); charMap.put("i", "ı"); charMap.put("s", "ş"); } public static void main(String[] args) { List<String> result = new ArrayList<>(); new SolrQueries().run("mohou", 0, "", result); System.out.println(result); } void run(String query, int idx, String cur, List<String> result) { if (idx == query.length()) { result.add(cur); return; } String letter = query.charAt(idx) + ""; if (charMap.containsKey(letter)) { run(query, idx + 1, cur + charMap.get(letter), result); } run(query, idx+1, cur + letter, result); }}`

1. it only goes from non-umlaut to umlaut version. Ideally it should also go the other way as well.

2. it only supports 1 mapping per character. There cases where a character could map to 2 different characters. This would require a different data structure to solve then a map for lookups (Hint: Union-Find)

Statistics: Posted by dendiz — Thu Feb 14, 2019 11:02 pm

]]>

A game where I lost no pawns (queen was promoted from a pawn)

Statistics: Posted by dendiz — Tue Feb 12, 2019 6:35 am

]]>

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

(this image was made by someone on the leetcode discussion forums)CODE:

`Input: n = 4, k = 2Output:[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]`

CODE:

`class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result = new ArrayList<>(); f(result, new ArrayList(), n, k, 1); return result; } void f(List<List<Integer>> result, List<Integer> temp, int n, int k, int s) { if (temp.size() == k) { result.add(new ArrayList<Integer>(temp)); return; } else { for(int i=s;i<=n;i++) { temp.add(i); f(result, temp, n, k, i + 1); temp.remove(temp.size() - 1); } } }}`

Statistics: Posted by dendiz — Tue Feb 12, 2019 5:01 am

]]>

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

This is a classical backtracking exhaustive search problem. There no shortcuts, you have to brute force through the entire search space. Given an integer n, return the number of distinct solutions to the n-queens puzzle.

But there are some space optimizations that we can do. Normally a NxN board would be represented by an NxN matrix, but we can use a Nx1 matrix and assign the index of a value to the row (or column). E.g

CODE:

`Q . .. Q .. . Q`

CODE:

`{0, 1, 2}`

CODE:

` int total = 0; public int f(int[] board, int idx, int n) { if (idx == n) { total++; return 1; } for(int i=0;i<n;i++) { if (isValid(board, idx, i)) { board[idx] = i; int r = f(board, idx + 1,n); } } return -1; }`

CODE:

` public boolean isValid(int[] board, int idx, int col) { for(int i=0;i<idx;i++) { if (board[i] == col) return false; if (Math.abs(i - idx) == Math.abs(board[i] - col)) { return false; } } return true } `

Statistics: Posted by dendiz — Mon Feb 11, 2019 11:07 pm

]]>

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:Example 2:

If you see a sorted array think binary search. I'll use a modified binary search to find the indices. The idea is this:Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

CODE:

`Input: nums = [5,7,7,8,8,10], target = 8Output: [3,4]`

CODE:

`Input: nums = [5,7,7,8,8,10], target = 6Output: [-1,-1]`

If the middle element is target then there are a couple of options.

1. middle is zero which means the are no elements to the left, so this is the start index.

1a. middle == a.length - 1 which means there are no elements to the right so this is the end index.

2. a[middle - 1] == target which means we have to continue searching on the left or right

3. a[middle - 1] != target (could be greater or less) this means middle is either the start or end.

otherwise just go left or right depending on the the middle item being greater or smaller than the target.

CODE:

`class Solution { public int[] searchRange(int[] nums, int target) { if (nums.length == 0) return new int[]{-1,-1}; int start = bs(nums, target, 0, nums.length-1, true); int end = bs(nums, target, 0, nums.length-1, false); return new int[]{start, end}; } int bs(int[] nums, int target, int start, int end, boolean s) { int mid = (start + end) / 2; if (start > end) return -1; if (nums[mid] == target) { if (s && mid == 0) return mid; if (!s && mid == nums.length - 1)return mid; if (s && nums[mid-1] < target) { return mid; } if (!s && nums[mid+1] > target) return mid; if (s) return bs(nums, target, start, mid-1, s); if (!s) return bs(nums, target, mid+1, end, s); } if (nums[mid] > target) { return bs(nums, target, start, mid-1, s); } if (nums[mid] < target) { return bs(nums, target, mid+1, end, s); } return -1; }}`

Statistics: Posted by dendiz — Mon Feb 04, 2019 11:56 pm

]]>

CODE:

`Input: 121Output: trueInput: -121Output: falseExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome.`

The idea is to get the last digit of the input and make this the first digit of a temp variable that I will use to compare against. Doing this for half of the digits will yield the result. E.g:

Input: 1221

halved: 12 | 21

get the last digit with input % 10 -> 1

make it the first digit of temp: temp = temp * 10 + last digit.

integer divide input by 10 to get to the next digit.

Do this for half of the digits. But how do you know when you've reached half? Each iteration the input decreases x10 and the temp increases 10x so

when temp > input it's done. E.g:

CODE:

`- Input: 12321 temp: 0- Input: 1232 temp: 1- Input: 123 temp: 12- input: 12 temp:123`

CODE:

` public boolean isPalindrome(int x) { if (x < 0) return false; if (x % 10 == 0 && x != 0) return false; int temp = 0; while(temp < x) { int r = x % 10; temp = temp * 10 + r; x = x/10; } // even number of digits e.g 1221 if (x == temp) return true; // odd number of digits e.g 121. temp will be 12 and x will 1, so temp/10 get rid // of last digit. if (temp/10 == x) return true; return false; } `

Statistics: Posted by dendiz — Tue Jan 29, 2019 7:31 am

]]>

Given a string s, find the longest palindromic subsequences length in s. You may assume that the maximum length of s is 1000.

I despise these types of questions. Who likes dynamic programming anyways?So the approach is the following:

Observation 1.

each 1 character subsequence is a palindrome.

Track the longest palindrome in substring(i, j) (i < j) as an entry in a 2D array with (i,j).

Due to observation 1. all items in the diagonal [i == j] will be 1. Get that out of the way

CODE:

` int[][] dp = new int[s.length()][s.length()]; for(int i=0;i<s.length();i++) { dp[i][i] = 1; }`

1. [bb]bab, b[bb]ab, bb[ba]b, bbb[ab]

2. [bbb]ab, b[bba]b, bb[bab]

3. [bbba]b, b[bbab]

4. [bbbab]

at each iteration notice that the previous iteration will contain the longest palindromic subsequence seen before it.

E.g iteration 2, step 2 b[bba]b:

bba is not a palindrome so the longest palindrome yet is the max of (bb, ba). ba is not a palindrome but bb is so the length is 2.

at each iteration if the char(i) == char(j) then the length of the palindrome will increase by 2 and will be 2 + the length of the previous palindrome.

So the dynamic programming relation is:

CODE:

`DP[i][j] = 1 if i == jDP[i][j] = 2 + DP[i+1][j-1] if char[i] == char[j]DP[i][j] = max(DP[i+1][j], DP[i][j-1])`

CODE:

` public int longestPalindromeSubseq(String s) { int[][] dp = new int[s.length()][s.length()]; for(int i=0;i<s.length();i++) { dp[i][i] = 1; } for(int d=1;d<s.length();d++) { for(int j=d;j<s.length();j++) { int i = j - d; if (s.charAt(i) == s.charAt(j)) { dp[i][j] = dp[i+1][j-1] + 2; } else { dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]); } } } return dp[0][s.length() - 1]; }`

1 to len(input). j defines the end of the window, and i defines the start of the window.

Statistics: Posted by dendiz — Thu Jan 24, 2019 2:41 pm

]]>

I actually didn't see the note about the input being the last significant bits, so I took me some trial error to realize that. So the numbers will beA character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For 1-byte character, the first bit is a 0, followed by its unicode code.

For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.

This is how the UTF-8 encoding would work:Given an array of integers representing the data, return whether it is a valid utf-8 encoding.CODE:

`Char. number range | UTF-8 octet sequence (hexadecimal) | (binary) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx`

Note:

The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.CODE:

`data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.Return true.It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.`

CODE:

`data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.Return false.The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.The next byte is a continuation byte which starts with 10 and that's correct.But the second continuation byte does not start with 10, so it is invalid.`

in the range of 0 - 255.

CODE:

` boolean testBit(int n, int x) { return ((n >>> x) & 1) == 1; }`

Next we just need to probe for the rules.

CODE:

` int fourByteMask = 0b000000000000000000000011110000; int threeByteMask = 0b000000000000000000000011100000; int twoByteMask = 0b000000000000000000000011000000; int nextMask = 0b000000000000000000000010000000;`

CODE:

`int req = 0; int i =0; while(i < data.length) { int cur = data[i]; if ((fourByteMask & cur) == fourByteMask && !testBit(cur, 3)) { req = 3; } else if ((threeByteMask & cur) == threeByteMask && !testBit(cur, 4)) { req = 2; } else if ((twoByteMask & cur) == twoByteMask && !testBit(cur, 5)) { req = 1; } else { req = 0; } if (req > 0) { while(req > 0) { i++; if (i > data.length - 1) return false; boolean c = testBit(data[i], 7) && !testBit(data[i], 6); if (!c) return false; req--; } i++; } else { if (testBit(cur, 7)) return false; i++; } } return true;`

Statistics: Posted by dendiz — Fri Jan 18, 2019 8:56 am

]]>

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Whenever you see "sorted array" think binary search.You may assume no duplicates in the array.

This is a typical binary search problem with an added requirement to return the insertion index.

If you trace a binary search start,end,mid pointers you will see that if the search is not successful the start pointer will be pointing to the insertion location.

CODE:

` public int searchInsert(int[] nums, int target) { if (nums.length == 0) return 0; int start = 0; int end = nums.length - 1; while(start <= end) { int mid = (start + end) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] > target) { end = mid - 1; } else { start = mid + 1; } } return start; }`

Statistics: Posted by dendiz — Wed Jan 16, 2019 8:52 am

]]>

Here is an image explaining the situation

The blue squares are the water trapped and the black are the bars trapping the water, the green numbers are the array values representing the heights.

The key observation here is that the max height bar will trap water depending on the max bars (relative to it self) on its right and left side.

Another observation is that the bar at location 'i' will trap water (minimum of [highest bar on right, higiest bar on left] - my own height) of water.

So here what we need to do:

- for each bar:
- find the height of the highest bar on the right
- find the height of the highest bar on the left
- total = min(rightmax, leftmax) - my height

for an index and onwards

CODE:

` for(int i=0;i<height.length;i++) { curMax = Math.max(height[i], curMax); leftMax[i] = curMax; }`

CODE:

`2,1,2,1,3,0,2,1,3`

CODE:

`2,2,2,2,3,3,3,3,3`

now just apply the algorithm above:

CODE:

` public int trap(int[] height) { int[] leftMax = new int[height.length]; int[] rightMax = new int[height.length]; int curMax = -1; for(int i=0;i<height.length;i++) { curMax = Math.max(height[i], curMax); leftMax[i] = curMax; } curMax = -1; for(int i=height.length-1;i>=0;i--) { curMax = Math.max(height[i], curMax); rightMax[i] = curMax; } int sum = 0; for(int i =0;i<height.length;i++) { sum += Math.min(rightMax[i], leftMax[i]) - height[i]; } return sum; }`

Statistics: Posted by dendiz — Wed Jan 16, 2019 8:29 am

]]>

Statistics: Posted by dendiz — Sun Dec 30, 2018 10:57 am

]]>

From trey@sage.org Fri Nov 29 18:00:49 2002

Date: Sun, 24 Nov 2002 21:03:02 -0500 (EST)

From: Trey Harris <trey@sage.org>

To: sage-members@sage.org

Subject: The case of the 500-mile email (was RE: [SAGE] Favorite impossible

task?)

Here's a problem that *sounded* impossible... I almost regret posting the

story to a wide audience, because it makes a great tale over drinks at a

conference. The story is slightly altered in order to protect the

guilty, elide over irrelevant and boring details, and generally make the

whole thing more entertaining.

I was working in a job running the campus email system some years ago when

I got a call from the chairman of the statistics department.

"We're having a problem sending email out of the department."

"What's the problem?" I asked.

"We can't send mail more than 500 miles," the chairman explained.

I choked on my latte. "Come again?"

"We can't send mail farther than 500 miles from here," he repeated. "A

little bit more, actually. Call it 520 miles. But no farther."

"Um... Email really doesn't work that way, generally," I said, trying to

keep panic out of my voice. One doesn't display panic when speaking to a

department chairman, even of a relatively impoverished department like

statistics. "What makes you think you can't send mail more than 500

miles?"

"It's not what I *think*," the chairman replied testily. "You see, when

we first noticed this happening, a few days ago--"

"You waited a few DAYS?" I interrupted, a tremor tinging my voice. "And

you couldn't send email this whole time?"

"We could send email. Just not more than--"

"--500 miles, yes," I finished for him, "I got that. But why didn't you

call earlier?"

"Well, we hadn't collected enough data to be sure of what was going on

until just now." Right. This is the chairman of *statistics*. "Anyway, I

asked one of the geostatisticians to look into it--"

"Geostatisticians..."

"--yes, and she's produced a map showing the radius within which we can

send email to be slightly more than 500 miles. There are a number of

destinations within that radius that we can't reach, either, or reach

sporadically, but we can never email farther than this radius."

"I see," I said, and put my head in my hands. "When did this start? A

few days ago, you said, but did anything change in your systems at that

time?"

"Well, the consultant came in and patched our server and rebooted it.

But I called him, and he said he didn't touch the mail system."

"Okay, let me take a look, and I'll call you back," I said, scarcely

believing that I was playing along. It wasn't April Fool's Day. I tried

to remember if someone owed me a practical joke.

I logged into their department's server, and sent a few test mails. This

was in the Research Triangle of North Carolina, and a test mail to my own

account was delivered without a hitch. Ditto for one sent to Richmond,

and Atlanta, and Washington. Another to Princeton (400 miles) worked.

But then I tried to send an email to Memphis (600 miles). It failed.

Boston, failed. Detroit, failed. I got out my address book and started

trying to narrow this down. New York (420 miles) worked, but Providence

(580 miles) failed.

I was beginning to wonder if I had lost my sanity. I tried emailing a

friend who lived in North Carolina, but whose ISP was in Seattle.

Thankfully, it failed. If the problem had had to do with the geography of

the human recipient and not his mail server, I think I would have broken

down in tears.

Having established that--unbelievably--the problem as reported was true,

and repeatable, I took a look at the sendmail.cf file. It looked fairly

normal. In fact, it looked familiar.

I diffed it against the sendmail.cf in my home directory. It hadn't been

altered--it was a sendmail.cf I had written. And I was fairly certain I

hadn't enabled the "FAIL_MAIL_OVER_500_MILES" option. At a loss, I

telnetted into the SMTP port. The server happily responded with a SunOS

sendmail banner.

Wait a minute... a SunOS sendmail banner? At the time, Sun was still

shipping Sendmail 5 with its operating system, even though Sendmail 8 was

fairly mature. Being a good system administrator, I had standardized on

Sendmail 8. And also being a good system administrator, I had written a

sendmail.cf that used the nice long self-documenting option and variable

names available in Sendmail 8 rather than the cryptic punctuation-mark

codes that had been used in Sendmail 5.

The pieces fell into place, all at once, and I again choked on the dregs

of my now-cold latte. When the consultant had "patched the server," he

had apparently upgraded the version of SunOS, and in so doing

*downgraded* Sendmail. The upgrade helpfully left the sendmail.cf

alone, even though it was now the wrong version.

It so happens that Sendmail 5--at least, the version that Sun shipped,

which had some tweaks--could deal with the Sendmail 8 sendmail.cf, as most

of the rules had at that point remained unaltered. But the new long

configuration options--those it saw as junk, and skipped. And the

sendmail binary had no defaults compiled in for most of these, so, finding

no suitable settings in the sendmail.cf file, they were set to zero.

One of the settings that was set to zero was the timeout to connect to the

remote SMTP server. Some experimentation established that on this

particular machine with its typical load, a zero timeout would abort a

connect call in slightly over three milliseconds.

An odd feature of our campus network at the time was that it was 100%

switched. An outgoing packet wouldn't incur a router delay until hitting

the POP and reaching a router on the far side. So time to connect to a

lightly-loaded remote host on a nearby network would actually largely be

governed by the speed of light distance to the destination rather than by

incidental router delays.

Feeling slightly giddy, I typed into my shell:

$ units

1311 units, 63 prefixes

You have: 3 millilightseconds

You want: miles

* 558.84719

/ 0.0017893979

"500 miles, or a little bit more."

Trey Harris

--

I'm looking for work. If you need a SAGE Level IV with 10 years Perl,

tool development, training, and architecture experience, please email me

at trey@sage.org. I'm willing to relocate for the right opportunity

Statistics: Posted by dendiz — Fri Dec 28, 2018 1:57 pm

]]>