Recent Entries 10
- pattern minor 112d agoProgram to check if strings are rotations of each other or notPlease review my code for above problem. I tried to cover the maximum possible boundary condition. Any optimizations or new easy and fast solution are welcome. ``` public class CheckStringAreRotationalyEquals { private static boolean areRotaionalyEquals(String s1, String s2) { boolean areRotaionalyEquals = Boolean.FALSE; int i = 0, j = 0; if ((s1 == null && s2 == null)) { areRotaionalyEquals = Boolean.TRUE; } else { if (s1 != null && s2 != null) { // if both the strings are not null then check for // are they rotaionaly equals if (s1.isEmpty() && s2.isEmpty()) { areRotaionalyEquals = Boolean.TRUE; } else if (s1.length() == s2.length()) { char ch2 = s2.charAt(j); boolean match = Boolean.TRUE; int count = 0; for (i = 0; i "); String s1 = "nullpointer"; String s2 = "ternullpoin"; boolean result = areRotaionalyEquals(s1, s2); System.out.println(result); s1 = "nullpointer"; s2 = "interponull"; result = areRotaionalyEquals(s1, s2); System.out.println(result); s1 = "nullpointer"; s2 = "rnullpointe"; result = areRotaionalyEquals(s1, s2); System.out.println(result); result = areRotaionalyEquals("", ""); System.out.println(result); result = areRotaionalyEquals("", "ternullpoin"); System.out.println(result); result = areRotaionalyEquals(null, ""); System.out.println(result); result = areRotaionalyEquals("", null); System.out.println(result); result = areRotaionalyEquals(null, null); System.out.println(result); result = areRotaionalyEquals("hodor", "orhod"); System.out.println(result); result = areRotaionalyEquals("sh", "hs"); System.out.pri
- pattern minor 112d agoMergesort that has `man 3 qsort` ANSI C prototypeI have taken a look at these review questions: one, two, three and four and would still like to ask you to review my implementation of mergesort that follows the `man 3 qsort` prototype. ``` void *malloc_or_exit(size_t size) { void *tmp = malloc(size); if (tmp == NULL) { if (size == 0) { return tmp; } fprintf( stderr, "Failed to malloc %zu bytes: %s", size, strerror(errno) ); exit(EXIT_FAILURE); } return tmp; } void mergesort0( void *xs, size_t n, size_t s, int (*cmp) (const void *, const void *) ) { if (n == 0 || n == 1) return; const size_t nlft = n / 2; const size_t nrgt = n - nlft; void *ys = (char *)xs + nlft * s; mergesort0(xs, nlft, s, cmp); mergesort0(ys, nrgt, s, cmp); void *const as = malloc_or_exit(n * s); void *const bs = (char *)as + nlft * s; void *const cs = (char *)as + n * s; memcpy(as, xs, n * s); void const *i = as; void const *j = bs; while (i != bs && j != cs) { if (cmp(i, j) int main() { int xs[] = {1, 2, 3, 4, 5}; int ys[] = {5, 4, 3, 2, 1}; int zs[] = {3, 1, 2, 4, 5}; int as[] = {1, 1, 1}; int bs[] = {3, 2, 2}; int len = 5; qsort(zs, len, sizeof(int), compare_int); for (int i = 0; i < len; ++i) { printf("%d ", *(zs + i)); } printf("\n"); } ```
- pattern minor 112d agoPerlin Noise terrain in Unity3DI've recently had time to devise another program so this time I decided to write the Perlin Noise algorithm in code. I have succeeded and the code works but I can't help but feel that my practices while writing are still not as good as they should be (especially since I'm still pretty new to the topic of programming). Please note that as I am working in Unity I have not separated the class files that I wrote into different source files. The code is comprised of a total of 3 class files: the main MonoBehaviour class named perlin_terrain and the two I have declared - named "Grid" and "Point". ``` using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class perlin_terrain : MonoBehaviour { public Terrain terrain; public int gridResolution = 512; // Will be adjusted to be divisible by the subdivision value. public int gridSubdivision = 4; // Value must be a power of 2. [Range(0, 1)] public float steepness = 0.12f; Grid grid; private static float[,] heights; // Use this for initialization void Start() { if (gridResolution unitPoints = new List(); unitPoints = getUnitPoints(x, y); int n = 0; foreach (Point point in unitPoints) { switch (n) { case 0: value1 = Vector2.Dot(point.GradientVector, distanceVectors[0]); break; case 1: value2 = Vector2.Dot(point.GradientVector, distanceVectors[1]); break; case 2: value3 = Vector2.Dot(point.GradientVector, distanceVectors[2]); break; case 3: value4 = Vector2.Dot(point.GradientVector, distanceVectors[3]); break; } n++; } weighed1 = Mathf.Lerp(value1, value2, fadeValue(pointX)); weighed2 = Mathf.Lerp(val
- pattern minor 112d agoJava function to rotate an image by 180 degreesI want to 180 rotate an Image. Here's what I wrote but it seems way too complicated. Is there any way to do this in a simpler way? ``` public void rotateImage180Deg() { for (int x = 0; x < width / 2; x++) { int y = width - 1 - x; for (int i = x; i < y; i++) { int offset = i - x; RGBColor top = imageMatrix[x][i]; imageMatrix[x][i] = imageMatrix[y][y - offset]; imageMatrix[y][y - offset] = top; RGBColor leftBottom = imageMatrix[y - offset][x]; imageMatrix[y - offset][x] = imageMatrix[i][y]; imageMatrix[i][y] = leftBottom; } } } ```
- pattern minor 112d agoRun Length Encoding (RLE) and Move To Front (MTF) in C++I have made two quite basic algorithms used for lossless data compression. This is my RLE: ``` #include std::string rle(const std::string& input) // encode (aaaaeecd -> 4a2e1c1d) { std::string output; int n = input.size(); int i = 0; while(i aaaaeecd) { std::string output; for(int i = 0; i < input.size(); i += 2) { int nb = (int)(unsigned char)input[i]; // range between 0 and 255 for(int k = 0; k < nb; k++) output += input[i+1]; } return output; } ``` and here goes my MTF: ``` #include #include #include #include /* if alphabet A = {'a', 'b', 'c'} then string "accbc" is encoded 02021 (a is at index 0, alphabet remains {'a', 'b', 'c'}, outputs 0 ; c is at index 2, alphabet becomes {'c', 'a', 'b'}, outputs 2 ; c is at index 0, alphabet remains {'c', 'a', 'b'}, outputs 0 ; b is at index 2, alphabet becomes {'b', 'c', 'a'}, outputs 2 ; a is at index 1, alphabet becomes {'a', 'b', 'c'}, outputs 1) */ std::string mtf(const std::string& input) { std::string output; std::list alphabet; // constant erase/insert for(int i = 0; i alphabet; // constant erase (begin) & operator[] ; insert (middle) is O(n) for(int i = 0; i <= 255; i++) alphabet.push_back((char)i); for(unsigned char n: input) { char temp_c = alphabet[n]; output += temp_c; alphabet.erase(alphabet.begin() + n); alphabet.insert(alphabet.begin(), temp_c); } return output; } ``` I know there are many possible improvments possible, especially for the RLE algorithm. I would just like a review on the C++ syntax I've used, especially on the structures I have chosen.
- pattern minor 112d agoFind lexicographical permutationsI have tried many possible methods here but I am still not able to reduce the time complexity of below algorithm. The basic layout of my problem is as follows: I have a string that is composed of only H's and V's. There can be not more than 10 H's and 10 V's possible. I need to find the Kth lexicographical order of such pattern. Also, inp[] array contains input is format: ``` 2 2 3 4 5 4 ``` which means that total H = 2, total V = 2 and I need to print 3rd lexicographical permutation of HHVV. Similarly for 4 5 4, I need to print 4th lexicographical permutation of HHHHVVVVV. ``` //This function returns the next lexicographical permutation of the StringBuilder s static StringBuilder getKRankString(StringBuilder s) { char ch[] = (s.toString()).toCharArray(); int i = 0, j=0; //This loop gets the highest i for which ch[i]ch[i] for(int k=s.length()-1;k>i;k--){ if(ch[k]>ch[i]){ j = k; break; } } //System.out.println(j); //swap characters at i and j char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; //Append the original string till i to reversed string from i till end StringBuilder swapped = new StringBuilder(new String(ch)); //System.out.println(swapped); String sb1 = swapped.substring(0, i+1); String sb2 = (new StringBuilder(swapped.substring(i+1, s.length())).reverse()).toString(); StringBuilder str = new StringBuilder(sb1+sb2); return str; } static String[] gridLand(String[] inp) { String[] outputArr = new String[inp.length]; for(int i=0;i<inp.length;i++){ //get the first line of input and get integer x and y int x = Integer.valueOf(inp[i].split(" ")[0]); int y = Integer.valueOf(inp[i].split(" ")[1]); int k = Integer.valueOf(inp[i].split(" ")[2]); StringBuilder sb = new StringBuilder(); //form the original string using x H's and y V's. //This will be the first String of this order for(in
- pattern minor 112d agoReturn all valid expressions with specific targetThe problem is stated as: Given a string that contains only digits 0-9 and a target value, return all expressions that are created by adding some binary operators (+, -, or *) between the digits so they evaluate to the target value. In some cases there may not be any binary operators that will create valid expressions, in which case the function should return an empty array. The numbers in the new expressions should not contain leading zeros. The function should return all valid expressions that evaluate to target, sorted lexicographically. For example: `digits = "123"` and `target = 6`, should return: `["1*2*3", "1+2+3"]` My current algorithm is below. I optimized it as much as I can. The question is base on code fights. My algo will generate all combinations of operands and operators accordingly. For the example above, it'll generate: Operands: ``` [['1', '2', '3'], ['1', '23'], ['12', '3'], ['123']] ``` Operators: ``` {0: [()], 1: [('+',), ('-',), ('*',)], 2: [('+', '+'), ('+', '-'), ('+', '*'), ('-', '+'), ('-', '-'), ('-', '*'), ('*', '+'), ('*', '-'), ('*', '*')]} ``` It then combines all possible combinations of operands and operators and evaluate each. For `digits = "1234506789"` and `target = 6`, it takes about 2.2 secs. It should be enough for code fights that has a limit of 4 sec, but I guess that also depends on the speed of the processor. But for some reason it still hits the time limit from the site. Thus Im trying to see how it can be optimized a bit more. Restrictions are: ``` 2 <= digits.length <= 10 -10^4 <= target <= 10^4 ``` My code is below. I commented out some of the alternatives I used, which pretty much has the same speed though. ``` from itertools import combinations, permutations import itertools import time def getExpression(digits, target): operation = { '+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, } seen = {} def calculate2(e,sign):
- pattern minor 112d agoBathroom stalls in C (Google Code Jam 2017)https://code.google.com/codejam/contest/3264486/dashboard#s=p2 Problem A certain bathroom has N + 2 stalls in a single row; the stalls on the left and right ends are permanently occupied by the bathroom guards. The other N stalls are for users. Whenever someone enters the bathroom, they try to choose a stall that is as far from other people as possible. To avoid confusion, they follow deterministic rules: For each empty stall S, they compute two values LS and RS, each of which is the number of empty stalls between S and the closest occupied stall to the left or right, respectively. Then they consider the set of stalls with the farthest closest neighbor, that is, those S for which min(LS, RS) is maximal. If there is only one such stall, they choose it; otherwise, they choose the one among those where max(LS, RS) is maximal. If there are still multiple tied stalls, they choose the leftmost stall among those. K people are about to enter the bathroom; each one will choose their stall before the next arrives. Nobody will ever leave. When the last person chooses their stall S, what will the values of max(LS, RS) and min(LS, RS) be? Input The first line of the input gives the number of test cases, T. T lines follow. Each line describes a test case with two integers N and K, as described above. Output For each test case, output one line containing Case #x: y z, where x is the test case number (starting from 1), y is max(LS, RS), and z is min(LS, RS) as calculated by the last person to enter the bathroom for their chosen stall S. Limits 1 ≤ T ≤ 100. 1 ≤ K ≤ N. 1 ≤ N ≤ 10^18. ``` Input Output 5 4 2 Case #1: 1 0 5 2 Case #2: 1 0 6 2 Case #3: 1 1 1000 1000 Case #4: 0 0 1000 1 Case #5: 500 499 ``` Description of my algorithm I attached a little graphic to show how the algorithm is suppose
- pattern minor 112d agoRotate a given number of variables in-placeA very simple but useful algorithm: rotate the values of a given number of variables in-place to the left so that the first variable gets the value of the second, the second gets the value of the third, etc... and the last variable gets the value of the first one. ``` #include #include template struct are_same: std::conjunction...> {}; template auto rotate_left_inner(T& first, T& second, Args&... args) -> T& { first = std::move(second); if constexpr (sizeof...(Args) == 0) { return second; } else { return rotate_left_inner(second, args...); } } template auto rotate_left(Head& first, Tail&... args) -> void { static_assert(are_same::value, "elements passed to rotate_left shall have the same type"); if constexpr (sizeof...(Tail) > 0) { auto tmp = std::move(first); auto& last = rotate_left_inner(first, args...); last = std::move(tmp); } } ``` This function can be used as follows: ``` int a=0, b=1, c=2, d=3, d=4; rotate_left(a, c, e); rotate_left(b, d); // Now (a, b, c, d, e) = (2, 3, 4, 1, 0) ``` The code above generated the same assembly than the hand-rolled version when I gave it five integers to rotate in the compiler explorer, with both GCC and Clang. I wanted to make a companion `rotate_right` function, but repeatedly finding the last element of a template parameter pack is not as easy, so the easiest solution for a programmer is to pass the variables to rotate to `rotate_left` in reverse order. Do you see any way to improve this simple algorithm? Anything that I might be missing?
- pattern minor 112d agoCalculate angle between planesI have written working code calculating the angle between the adjacent planes. I read subsequently from standart input: n - amount of triangles, m - amount of vertices ind[] - indices of the vertices given coord[] - coordinates of the vertices given The output is supposed to be the maximum angle between the adjacent planes in rad. Function calculate_angle() iterates over the amount of triangles so that I compare only new ones with the old ones (for z in range(k, n)) list_result = [i for i in index1 if i in index2] used for the adjacency detection: it asks, whether the indices of the first triangle coordinates == to the second. If there are at leat 2 of them - we start to calculate the normals to triangles (the angle between surfaces = to the angle between their normals) However, if the number of triangles is more than 104 it starts to work very slowly: ``` import numpy as np import math import sys import cProfile, pstats, io pr = cProfile.Profile() pr.enable() num_triangles, num_vertices = input().split() n = int(num_triangles) # amount of triangles m = int(num_vertices) # amount of vertices ind = [] coord = [] angles_list =[] for i in range(n): ind.append([int(j) for j in input().split()]) # indices of the vertices given for j in range(m): coord.append([float(k) for k in input().split()]) # coordinates of the vertices given def unit_vector(v): # Returns the unit vector of the vector. return v/ np.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]) def angle_between(v1, v2): v1_u = unit_vector(v1) v2_u = unit_vector(v2) return math.acos(max(min(np.dot(v1_u, v2_u), 1), -1)) # (np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) def calculate_angle(): for k in range(0, n): for z in range(k, n): index1 = ind[k] index2 = ind[z] trignum =0 list_result = [i for i in index1 if i in index2] if (ind[k] != ind[z])&(len(list_result) >= 2)&(trignum <= 3): trignum = trignum +