if-statement,language-agnostic

There are 2 reasons why order may matter: multiple branches of several if/else_if/else_if/else statement have different probability due to known distribution of data Sample - sort apples, most are good yellow once (90%), but some are orange (5%) and some are of other colors (5%). if (apple.isYellow) {...} else if...

math,language-agnostic,programming-languages,symbolic-math

i=10 i=i+1 i=i+1 i=i+1 In mathematics, A=B is not an assignment of the value of B to A. It instead expresses an identity. The expression i=i+1 just doesn't make sense mathematically. One exception is boolean algebra, where 0+0=0 and 0+1=1+0=1+1=1. But then the initial identity i=10 doesn't make any...

language-agnostic,arithmetic-expressions

Yes. Here is a quick example: http://my.safaribooksonline.com/book/hardware/9788131732465/instruction-set-and-instruction-timing-of-8086/app_c those are the microcode and the timing of the operation of a massively old architecture, the 8086. it is a fairly simple point to start. of relevant note, they are measured in cycles, or clocks, and everything move at the speed of the...

language-agnostic,scoring,question-answering

if you allow free text (that is good in my opinion - because the user may have some good explanation (maybe some you have missed) why he choses a multiple choice answer you considered to be false) you should correct it by hand. Because trying to match the free answer...

algorithm,language-agnostic,graph-algorithm

Tarjan algorithm for searching strongly connected components of a directed graph http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm allows you to make the distinction you need.

algorithm,sorting,language-agnostic,ranking,choice

This is the Assignment problem. You could use, for instance, the Hungarian Algorithm. You just need to come up with a way to turn the user/player preferences into costs. Perhaps when a person gets their first choice, the cost is -3, second choice is -2, third choice is -1, etc....

C++ requires a few things that aren't required in something like C. For example, it typically involves some overhead for exception handling. Although it may not be strictly required, most systems have at least a tiny bit of a top-level exception handler to tell you that the program shut down...

If you look at the RevEng 16-bit CRC Catalogue, you see that there are two different CRCs called "CCITT", one of which is labeled there "CCITT-False". Somewhere along the way someone got confused about what the CCITT 16-bit CRC was, and that confusion was propagated widely. The two CRCs are...

performance,language-agnostic,big-o

Adding an immutable contiguous container of length A to one of length B normally takes O(A+B) time. This is because the resulting container will need to be built anew, and is of length A+B. Consider the ith addition of the given loop. The string will be of length i-1, and...

I'd divide the value by 45°, round, and then multiply back by 45°. Pseudocode: deg = round(deg / 45) * 45; Assumption: the / operator returns a floating-point representation and does not perform integer division. If the specific language does not treat it like this it should be handled explicitly...

c,scripting,lua,language-agnostic,scripting-language

They should interact with the various "programming primitives" that the native code implements. That is, the native code should only do enough to allow the scripts to function within the game (although "function" can sometimes mean speed-wise). If that sounds cyclical... it is. There's no complete way to define at...

algorithm,math,language-agnostic,equation,polynomial-math

Solving several polynomial equations in several variables is a hard problem. Doing so in polynomial time in the average case is Smale's 17th problem. It is unlikely that you will find a fast and simple algorithm for doing so that actually works. You might look at "Ideals, varieties, and algorithms"...

This is not specific to any one DB API. TL;DR: Don't pass "SQL fragments" around. Rather than passing complete clauses fro a select statement, or (sub-)expressions to add into a select clause, pass the components keeping the user data separate from the identifiers. In this case do not pass name...

performance,swift,language-agnostic,arithmetic-expressions

Performance There's necessarily a cost to that kind of verification. At the lowest level, the operation which causes the overflow takes a single CPU operation. Checking that there was or not and overflow during this operation requires at least one more operation (e.g. using jump operations (branching) which consider the...

algorithm,language-agnostic,dynamic-programming

The O(nT) running time gives you the hint: do dynamic programming on two axes. That is, let f(a,b) denote the maximum sum <= b which can be achieved with the first a integers. f satisfies the recurrence f(a,b) = max( f(a-1,b), f(a-1,b-s_a)+s_a ) since the first value is the maximum...

python,language-agnostic,artificial-intelligence,cluster-analysis

There is a tutorial on how to implement such an algorithm in ELKI: http://elki.dbs.ifi.lmu.de/wiki/Tutorial/SameSizeKMeans Also have a look at constraint clustering algorithms; although usually these algorithms only support "Must link" and "cannot link" constraints, not size constraints. You should be able to do a similar modification where you first specify...

text,language-agnostic,hex,translation

What is it that you're using to convert the text to that string of Hex? Regardless, it would appear as though the Hex output is peppered with various CC commands. Just looking at the codes in the format document to which you linked I get the following: Timecode 00:00:00:00: start...

sockets,unicode,utf-8,language-agnostic,websocket

This is the logic I wound up using (in JavaScript): function incompleteUTF8(buf) { for(var ix = Math.max(buf.length - 6, 0); ix < buf.length; ix++) { var ch = buf[ix]; if(ch < 0x80) continue; if((ch & 0xe0) === 0xc0) ix++; else if((ch & 0xf0) === 0xe0) ix += 2; else if((ch...

language-agnostic,floating-point,floating-point-precision,ieee-754

From the Wikipedia entry on IEEE-754: The number representations described above are called normalized, meaning that the implicit leading binary digit is a 1. To reduce the loss of precision when an underflow occurs, IEEE 754 includes the ability to represent fractions smaller than are possible in the normalized representation,...

algorithm,language-agnostic,geometry

Algorithm: int area(int[] T) { int area = 0; int x = 0; for (int i = 0; i < T.length; i += 2) { x += t[i]; area += x * t[i + 1]; } return Math.abs(area); } Description: Our polygon is closed in a big rectangle. Based on...

matches = ["An", "Apple", "A", "Day"]; if (matches.indexOf(x) > -1){ return true; } else{ return false; } ...

algorithm,math,language-agnostic,number-theory

The way I'd implement something like this is to store the aspect ratios (1:144, 2:72, 3:48, 4:36, etc.) into a sorted array. Then for each incoming image, calculate its aspect ratio, then find the nearest desired ratio using binary search. Even better, store the log of the aspect ratios, and...

java,math,language-agnostic,distance

This is pretty simple: You move diagonally towards the goal until you're either on the same row or same col. This will be min(dx, dy) steps. Let's call this d (for diagonal steps) Then you move on a straight line towards the goal. This will be max(dx, dy) - d...

c++,assembly,language-agnostic

It depends on how the virus was developed, but as an example, in assembly, this: UnusedString DB 'Concept Virus(CV) V.5, Copyright(C)2001 R.P.China.', 0 will embed the string (null terminated) into the object code and executable file. Whether or not the code actually references UnusedString is meaningless to most assemblers (in...

language-agnostic,programming-languages

It's certainly not a bad thing, per se, as learning of advanced matters ahead of time can really help you along the road. This isn't even confined to computer science; I, for example, find myself in this position all the time when cooking a new dish or studying relatively advanced...

In ASCII, a Horizontal Tab is code 9. The ASCII Horizontal Tab is code 9 regardless of what character set the code is written in. In C, '\t' is the horizontal tab in the character set of the source code, regardless of the character set of the IO. the integer...

math,graphics,language-agnostic,collision-detection,trigonometry

I can imagine 4 different resolutions of what you have, and it is unclear which one you want. Here they are, where the black arrow is the movement of the centre of the ball between the frame before collision and the frame you are asking how to draw. A) the...

The Trick: Splitting vs. Matching This is one of those questions that look hard if you try to match the text. The trick is to match the emails, and the adjoining spaces, and to split on that. You can split using this regex: (?i)\s*\b[A-Z0-9._%+-][email protected][A-Z0-9.-_]+\.[A-Z]{2,6}\b\s* In the demo, the colored bits...

javascript,html,web,language-agnostic

Rhumborl wrote: "backwards-compatibility of non-existent standards, basically", which is simplistic but true. The Wikipedia overview article on the history of web browsers says, after summarising the browser wars: The wars put the Web in the hands of millions of ordinary PC users, but showed how commercialization of the Web could...

language-agnostic,rsa,number-theory,modular-arithmetic

Well, sort of... Suppose that you have determined the number "d" such that d*e=1 (mod phi(n)) Where phi(n) is the size of the set of relatively prime numbers relative to n. For example, if n=pq where p and q are prime, then phi(n)=(p-1)*(q-1). Then m=c^d (mod n) In the case...

oop,language-agnostic,nomenclature

It is called the “subject” following the subject-verb-object sentence structure that object-oriented programming mimics: cat.meow(10, x); |_||___||_____| | | | | | +--> object (the arguments list is a tuple object) | | | +--> verb (the verb is the method name with the dot) | +--> subject (quite self...

arrays,algorithm,sorting,data-structures,language-agnostic

Actually modifying quickselect is not needed. If I had an array (called arrayToSearch in this example) and I wanted the k smallest items I'd do this: int i; int k = 10; // if you wanted the 10 smallest elements int smallestItems = new Array(k); for (i = 0; i...

java,language-agnostic,naming-conventions,method-overloading

In my opinion, using verbose method name is a better solution. It's more understandable, your code will require less comments It's easier to maintain, you can change the implementation without impacting existing signatures. You still can add a new signature, without regression. But be careful, in some situation it's preferable...

Just navigate to Source > Format and click on format it automatically format the whole function. Shortcut : Alt+Shift+f Make sure you have done all formatting . Link for detail formatting : https://blogs.oracle.com/netbeansphp/entry/formatting_tabs_and_indents...

language-agnostic,linked-list,singly-linked-list

Based on your comments I suppose you are asking about arithmetic mean (http://en.wikipedia.org/wiki/Mean#Arithmetic_mean_.28AM.29 ) Also if you know how many elements are there you can get rid of count. Node current = root; double sum = 0; int count = 0; while (current != null) { sum += current.el; count++;...

database,language-agnostic,disk-io

If you want SQLite to handle that many records, you have to batch them in transactions. See http://sqlite.org/faq.html#q19 But I suspect you don't need to record that much data, if all you want is the information about which channels are empty....

language-agnostic,uml,class-diagram

TL;DR You can omit the type and it is not obligatory, sometimes you even don't know the exact types or you just don't care, e.g. in uml-diagrams.org: Library Domain Model, UML Class Diagram Example UML 2.4.1 Infrastructure specification says: ...10.2.5 Property ...A property is a typed element that represents an...

language-agnostic,iterator,random-sample

Encryption is reversible, hence an encryption is a one-to-one mapping from a set onto itself. Pick a block cypher with a large enough block size to cover the number of items you have. Encrypt the numbers 0, 1, 2, 3, 4, ... This will give you a non-repeating ordered list...

algorithm,optimization,language-agnostic,number-theory

an divides all previous elements if and only if it divides the greatest common divisor of those elements. So you need to keep track of gcd(a1, a2, ..., an) and the minimum an for which an | gcd(...)....

Use an algorithm to generate combinations of size K from the set of N. (Pick any from the SO question: Algorithm to return all combinations of k elements from n). Using the result, apply Heap's Algorithm to create all permutations of this k-element subset (or another Algorithm to generate...

algorithm,language-agnostic,dynamic-programming

Assuming that you can solve the following problem: Ending at cell (i, j) is there any palindrome with different length horizontally and vertically. Hint for above problem: boolean[][][]palindrome;//Is there any palindrome ending at (i , j) has length k for(int i = 0; i < n; i++){ for(int j =...

language-agnostic,metrics,coefficients

As originally defined by Jaccard, the similarity coefficient is the size of the intersection divided by the size of the union. Since both are sizes, a negative result obviously isn't possible. What you show in the question looks sort of like the Jaccard similarity for a bit vector. However, for...

algorithm,language-agnostic,utf

I think the question is more interesting than the comments suggest: UTF-8 -> UTF-16: It's not possible if you write UTF-16 word by word (if you write byte by byte, I think it depends on UTF-16LE vs. UTF-16BE). UTF-8 encodes 7 bit with 1 byte, 11 bit with 2 bytes...

language-agnostic,zlib,deflate

We may never know. The developer of the deflate format, Phil Katz, passed away many years ago at a young age. My theory is that a match length was limited to 258 so that a match length in the range 3..258 could fit in a byte, encoded as 0..255. This...

algorithm,sorting,language-agnostic,quicksort

I claim that m1 <= m2 is necessary and sufficient. If it is the case, after the first we can be sure that m2 smallest numbers from the m1 + 1 ... n part are located inside the 1 ... m1 + m2 prefix. m2 >= m1, thus m1 smallest...

methods,language-agnostic,parameter-passing

Of course, there is Smalltalk which is really expressive with its keyword messages... n := collection size // 2. head := collection copyFrom: 1 to: n. Other than that, you will find that in ADA or Python, and probably some others you can prefix each argument with a key (which...

algorithm,sorting,language-agnostic,pseudocode

Anecdotally, most loops can be represented by summation. In general this isn't true, for example I could create the loop for(int i = n; i > 1; i = ((i mod 2 == 0) ? i / 2 : 3 * i + 1))) i.e. initialize i to n, on...

language-agnostic,byte,probability,magic-numbers

Capture real-world data from a diverse set of inputs that would be used by applications of your library. Write a quick and dirty program to analyze dataset. It sounds like what you want to know is which bytes are most frequently totally excluded. So the output of the program would...

math,vector,language-agnostic,geometry

Normalize direction vector, if needed: Len = Sqrt( dirx^2 + diry^2 ) dx = dirx / Len dy = diry / Len then find endpoint: end_x = x0 + 40 * dx end_y = y0 + 40 * dy ...

I think what you want is the dihedral angle. These are well know and you can see a table at https://en.wikipedia.org/wiki/Table_of_polyhedron_dihedral_angles . For an Icosahedron the angle is π − arccos(√5/3) or approximately 138.19°. The angle in your diagram is 360° - 138.19° - 90° - 90° = 41.81°.

oop,design-patterns,language-agnostic

You are correct that in most OO languages, inheritance and polymorphism go one with another. But: Polymorphism and Inheritance both illustrate different aspects. Polymorhpism shows how the types can stand one for another in operations, while the inheritance shows the relationship between the types. Polymorphism and Inheritance don't have to...

syntax,language-agnostic,grammar,bnf,ebnf

Braces and brackets are EBNF constructs -- the E stands for extended. Simple BNF is just a context-free grammar with no extra syntactic sugar for recursive things, so you have to write it out with a nested recursive rule: <function parameter list> ::= ( <param-list> ) | ( ) <param-list>...

c#,string,algorithm,optimization,language-agnostic

I decided to add this answer not because it is the optimal solution to your problem, but to illustrate two possible solutions that are relatively simple and that are somewhat in line with the approach you seem to be following yourself. The (non-optimized) sample below provides an extremely simple prefix...

javascript,language-agnostic,multipleselection

I have implemented the boolean isSelected property and as the application grew, I built more and more functions which applied to all elements. In each function, I had to put a for loop which would make sure to only alter selected items. I'll write some kind of pseudo-code to keep...

algorithm,sorting,language-agnostic,order,priority

Perhaps you could use a legal-style paragraph numbering.: 1, 1.12, 1.12.1, 1.12.2, 1.12.2.5 and so on. You can always insert a new entity between existing entities by extending to a new level of '.1'. Quite how you stop users assigning absurdly high priorities to otherwise routine documents is another problem....

c#,exception,logging,exception-handling,language-agnostic

Better use a logging framework like Log4Net. Also, there is a very small chance of running into exceptions in using the TextWriter class. You just have to make sure that: Your paths and permissions are correct when opening the stream/TextWriter in the first place. Your TextWriter object is not Disposed...

algorithm,language-agnostic,big-o,time-complexity,combinations

First, there is nothing wrong with using O(n! / (n-k)!k!) - or any other function f(n) as O(f(n)), but I believe you are looking for a simpler solution that still holds the same set. If you are willing to look at the size of the subset k as constant, for...

algorithm,sorting,language-agnostic

The Dutch National Flag Problem is just a special case of the more general sorting problem where the only permissible elements are 0, 1, and 2. You can absolutely solve it using a standard sorting algorithm. The problem is interesting in of itself partially for historical reasons but largely because...

io,language-agnostic,consistency,os-agnostic

Yes, writes that appear sequential (to you) can be reordered before being written to disk, primarily because the order seen by your code (or even the OS) may not correspond directly to locations on the disk. Although IDE disks did (at one time) use addressing based on specifying a track,...

Since it's a homework problem I'm not going to give you the answer but you might want to read up on Dijkstra's algorithm and the A* algorithm as well as the related graph search algorithms in the sidebars of those pages.

c,language-agnostic,bit-manipulation

It is possible to repeatedly compute x & (x << 1) until the result becomes 0. The number of iterations is the count of highest bits set. From there, to get the start and end index, looking at the previous to the last iteration gives the start index, adding the...

html,sql,language-agnostic,coding-style

ID numbers are generally assigned arbitrarily by the database (e.g. with MySQL AUTO_INCREMENT), and they're just accidents of timing. It's generally a bad idea to depend on them and hard-code them into your code. The corresponding name is less likely to change, so if you have to hard-code something, that's...

winapi,language-agnostic,winsock,endianness

The addresses contained in the hostent structure are in network byte order. If you have code that suggests otherwise then you are misinterpreting that code and reaching the wrong conclusion. In network byte order, on a little endian host, 127.0.0.1 is 0x0100007f. To see how this works, remember that on...

algorithm,language-agnostic,time-complexity,complexity-theory,analysis

Answering for the first part :- for i = 1 to 526 for j = 1 to n^2(lgn)^3 for k = 1 to n x=x+1 This program will run 526 * n^2 * (lg n)^3 * n times = 526 * n^3 * (lg n)^3 times. So, x = x...

It depends on the particular task and class usage. If your design is about UI only and these classes are ViewModels than GeneralOption would work. It makes sense to introduce new class if you suspect child entity can be extended in the future or you need additional data to be...

java,oop,design-patterns,dependency-injection,language-agnostic

The point with Dependency Injection and more specifically the Dependency Inversion Principle is that you don't want all types in your application to depend on other concrete types. Not only does this hinder testability, but also maintainability and flexibility. No matter what you do, and no matter how many abstractions...

design-patterns,language-agnostic,singleton

The word Singleton by definition(of Design Patterns) does not allows multiple instances, but yeah you can tweak the class to create multiple instances but then it won't be considered as a Singleton by definition

android,linux,dns,language-agnostic

There is no OS level DNS cache in Android, see http://android.stackexchange.com/questions/18002/is-there-a-way-to-list-the-local-dns-cache Edit: it apparently depends on the Android version. Current releases use Bionic DNS caching, see http://osxr.org/android/source/bionic/libc/netbsd/resolv/res_cache.c You can access the cache with __get_res_cache. This is an in-memory, per-process cache. If you have access to the configured recursive resolver, you...

algorithm,language-agnostic,job-scheduling,greedy

In fact, neither "earliest deadline first", "highest profit first" nor "highest profit/duration first" are correct algorithm... Assume 2 jobs: Job A has profit 1, time duration 1, deadline before day 1; Job B has profit 2, time duration 2, deadline before day 2; Then "earliest deadline first" fails to get...

performance,language-agnostic,programming-languages

Short version There is no correct answer because your question is not specific enough (the two examples of code you give don't achieve the same purpose). If your question is: Is bool isGreater = (a > b); slower or faster than int sum = a + b;? Then the answer...

database,language-agnostic,global-variables

A database is just global data if you have global database accessors, which is wrong. Technically a database is a data store to persist application data, that is, to preserve it between executions of the same code (as opposed to in-memory data). The data in the database is not meant...

algorithm,language-agnostic,binary,compression,storage

The information-theoretic minimum for storing 100 different values is log2100, which is about 6.644. In other words, the possible compression from 7 bits is a hair more than 5%. (log2100 / 7 is 94.91%.) If these pairs are simply for temporary storage during the algorithm, then it's almost certainly not...

Finally is actually very useful. It is definitely a worthy tool to have around, as it essentially works to protect resources that must be managed without waiting for the garbage collector. There are other uses, but this is its primary one. Why should we use it though? Why not just...

This is typical of functional languages where the function returns the last evaluated expression. In an imperative context, this is an impractical restriction, since it is common to return early, for example when seeing if an array contains a certain element contains(array, element) { for(el in array) { if(el ==...

In all kinds of code. The constant NaN is explicitly of type "number". The value NaN should not be taken to mean what the colloquial phrase "not a number" means. Instead, it's a specific term from the IEEE floating point spec that describes a family of values whose bit arrangements...

language-agnostic,cellular-automata

It's a cellular automaton with 5 states. The rule is 3457/357/5 using golly's notation. It has 5 states: 0, 1, 2, 3, 4. In each step, cells behave as follows: 0 -> 1 if 3, 5 or 7 of its eight neighbors are 1, or 0 otherwise 1 -> 1...

scripting,language-agnostic,tcl,interpreter

Tcl, unlike a number of other languages, processes comments at the same time as the rest of its syntax. This means that, because it came across a { first (as part of the proc command invocation) it is focusing on matching up the braces. It only comprehends a # as...

python,unit-testing,oop,language-agnostic,private

In a theoretical point of view, you only need to test public methods of your instantiable classes (in standard OOP languages). There is no point in testing the internal behaviour because all you want is "which output for that input" (for a particular method, or for the entire class). You...

unicode,language-agnostic,compatibility,robustness

The first example which comes to my mind: If you create a file under OSX that is named é (single U+00E9 codepoint), the OS will store it actually as U+0065 U+0301 (Unicode decomposition). The file will be still accessible under the original name, but listed as decomposed. How to avoid:...

design,architecture,language-agnostic

Case 1: bar() also panic when hasBar() is false This will not be surprising behavior to me as if I am not assigning anything to a float, I shouldn't be expecting anything in return form it. Returning NaN is a convenient way to avoid exception in program and letting it...

The first object oriented language was Simula. Specifically Simula67, introduced in 1967 and implemented in 1968. Simula67 added the concept of classes and subclasses (inheritance) inspired by a research paper (theory, not any specific language) by C.A.R. Hoare describing the concept of classes as a collection of data in memory...

null,linked-list,language-agnostic,programming-languages,non-nullable

One solution could be using something that is equivalent to the Maybe type. It has either the value Just x, where x in this case is the next node in the list, or Nothing. The Maybe monad is best demonstrated in Haskell. http://learnyouahaskell.com/a-fistful-of-monads...

Yes, it is possible. You can use a special data structure that can be constructed in linear time and answers a range maximum query in O(1). It is rather complex, you can read about it here. When we have this data structure, we can use binary search to find the...

algorithm,language-agnostic,graph-algorithm

What you are looking for is called the minimum cut of a graph. By the Max-flow_min-cut_theorem the value of the minimum cut is equal the the value of the maximum flow. Computing the maximum flow in a network is a standard problem and there are several algorithms for computing this...

algorithm,language-agnostic,combinations

Finding the comnbination is also done via backtracking. At each step - you "guess" if you should or should not add the current candidate element, and recurse on the decision. (and repeat for both "include" and "exclude" decisions). Here is a jave code: public static int getCombinations(int[] arr, int maxSize)...

algorithm,math,language-agnostic,functional-programming,formula

Note that the most circles with radius R contain less than πR² integer points within the boundary, so usually that map doesn't exist. Reference: Gauss circle problem And I suspect that even for good R values there is no simple formula, only iterative aprroach (look at (1) formula in the...

language-agnostic,primality-test

Yes, all primes are of the form 6k +/- 1, but that doesn't mean that each number that is of the form 6k +/- 1 is prime. Consider 25, which is 6 * 4 + 1. Clearly, 25 is not prime.

math,count,language-agnostic,numbers,sequence

So first you want all numbers with the digits 0 in order. i.e. just 00 Then all numbers with the digits 0,1: 00, 01, 10, 11 but excluding 00 Then all numbers with digits 0,1,2: 00, 01, 02, 10, 11, 12, 20, 21, 22 but excluding 00, 01, 10, 11...

algorithm,language-agnostic,ascii

The following code should work in C and C++: int codeFor(char ch) { if (ch >= 'A' && ch <= 'Z') { return ch - 'A'; } else if (ch >= 'a' && ch <= 'z') { return ch - 'a'; } else { /* do something to report an...

language-agnostic,promise,lazy-evaluation,future

Both promises and "lazily evaluated objects" are forms of proxies. Proxy is the key word here. A proxy means "a placeholder for an actual object value" A promise is a synchronicity constrained proxy for a value. Some libraries like Kris Kowal's Q-Connection even let you proxy remote object with promises,...

algorithm,language-agnostic,time-complexity

When you extract a vertex from the heap, you then need to examine all the edges coming out of that node and do some processing for each neighbour (decreasing key). This means that we end up examining all edges during the entire algorithm, and may require O(logV) for each edge,...