body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I just took a stab at creating a library for something I'm dubbing semi-synchronous programming (async + dependencies). It's rather dense, but I'd really appreciate a quick code review to ensure I'm not introducing any race conditions. Feedback on best practices, general improvements is also welcome.</p>
<pre><code>from multiprocessing import Queue, Process, Manager
from collections import defaultdict
from time import sleep
def queue_function(fn, args, kwargs):
semisync.q.put([fn(*args, **kwargs), id(fn)])
def start_process(fn, args, kwargs):
p = Process(target=queue_function, args=(fn, args, kwargs))
p.start()
semisync.processes.append(p)
def cleanup():
# ensure no processes remain in a zombie state
while semisync.processes:
p = semisync.processes.pop()
p.join()
def generate_dependency_trees(tree):
for fn in tree.keys():
for dependency in tree[fn].get('dependencies', []):
semisync.depends_on[fn].add(dependency)
semisync.needed_for[dependency].add(fn)
def dependencies(fn):
tree, completed = semisync.tree, semisync.completed
return [d for d in tree[fn]['dependencies'] if d not in completed]
def independent_fns(tree):
result = []
for key in tree.keys():
if not dependencies(key):
result.append(key)
return result
# wrap method in fn to call semisynchronously
def semisync_method(c, method_name):
def method(*args, **kwargs):
getattr(c, method_name)(*args, **kwargs)
return method
def merge_dicts(d1, d2):
for key in ['args', 'kwargs']:
d1[key] += d2.get(key, [])
return d1
class semisync:
tree = {}
q = Queue()
processes = []
map = {}
manager = Manager()
depends_on = defaultdict(set)
needed_for = defaultdict(set)
completed = set()
fn_map = {}
lock = manager.Lock()
def __init__(self, callback=False, dependencies=set()):
self.callback = callback
self.dependencies = dependencies
def __call__(self, fn):
"""Returns decorated function"""
def semisync_fn(*args, **kwargs):
fn_call = {'callback': self.callback, 'args': [args], 'kwargs': [kwargs],
'dependencies': set([semisync.map[d] for d in self.dependencies])}
semisync.tree[fn] = merge_dicts(fn_call, semisync.tree.get(fn, {}))
# functions cannot be added to queue
# work around this by passing an id inst
semisync.fn_map[id(fn)] = fn
#mapping from decorated function to undecorated function
semisync.map[semisync_fn] = fn
return semisync_fn
@classmethod
def clear(self):
semisync.completed = set()
semisync.depends_on = defaultdict(set)
semisync.needed_for = defaultdict(set)
@classmethod
def begin(self):
# applies fn(*args) for each obj in object, ensuring
# that the proper attributes of shared_data exist before calling a method
# because some functions depend on the results of other functions, this is
# a semi-synchronous operation -- certain methods must be guaranteed to
# terminate before others
# aliasing
completed = semisync.completed
tree, q, processes = semisync.tree, semisync.q, semisync.processes
depends_on, needed_for = semisync.depends_on, semisync.needed_for
fn_map = semisync.fn_map
generate_dependency_trees(tree)
# start a new process for each object that has no dependencies
for fn in independent_fns(tree):
for i in range(len(tree[fn]['args'])):
args, kwargs = tree[fn]['args'].pop(), tree[fn]['kwargs'].pop()
start_process(fn, args, kwargs)
# read from queue as items are added
i = 0
while i < len(processes):
# update note with new data
result, fn_id = semisync.q.get()
fn = fn_map[fn_id]
completed.add(fn)
#execute callback
if tree[fn]['callback']:
tree[fn]['callback'](*result)
# iterate through objects that depended on the completed obj
# and remove the completed object from the list of their dependencies
for other_fn in needed_for[fn]:
depends_on[other_fn].remove(fn)
# if any objects now have zero dependencies
# start an async process for them
if not depends_on[other_fn]:
for j in range(len(tree[other_fn]['args'])):
args, kwargs = tree[other_fn]['args'].pop(), tree[other_fn]['kwargs'].pop()
start_process(other_fn, args, kwargs)
i += 1
cleanup()
</code></pre>
<p>Usage is as follows:</p>
<pre><code>from semisync import semisync
from multiprocessing import Manager
from random import random, randint
from time import sleep
# shared data between processes
shared = Manager().Namespace()
# a demo callback function
def output(field, value):
print field + ": $" + str(value)
# simple callback syntax
@semisync(callback=output)
def revenue():
# simulated api call
sleep(random())
shared.revenue = randint(1, 1000)
return "Revenue", shared.revenue
@semisync(callback=output)
def expenses():
# simulated api call
sleep(random())
shared.expenses = randint(1, 500)
return "Expenses", shared.expenses
# will run only when revenue() and expenses() have completed
@semisync(callback=output, dependencies=[revenue, expenses])
def profit():
shared.profit = shared.revenue - shared.expenses
return "Profit", shared.profit
# queue function calls
revenue()
expenses()
profit()
# executes queued calls semi-synchronously
semisync.begin()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-20T07:42:30.650",
"Id": "178259",
"Score": "0",
"body": "You should check out the new 3.5 keywords."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-20T20:55:16.607",
"Id": "178402",
"Score": "1",
"body": "I actually have! Also realized that concurrent.futures exists, haha."
}
] |
[
{
"body": "<p><a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow\">PEP0008</a> says to use 4 spaces per indentation level. Using just 2 can make it harder to see what is and isn't a full indentation.</p>\n\n<p>You should use <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">docstrings</a>, especially since for <code>cleanup</code> you wrote a comment that could be one if it was formatted as a docstring. They're basically comments that are programmatically accessible so that someone else using your script can read what the function does.</p>\n\n<pre><code>def cleanup():\n \"\"\"Ensure no processes remain in a zombie state\"\"\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-26T12:05:02.210",
"Id": "101963",
"ParentId": "39315",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:09:05.763",
"Id": "39315",
"Score": "6",
"Tags": [
"python",
"asynchronous"
],
"Title": "Semi-synchronous programming in Python"
}
|
39315
|
<p>The first thing I would like to say is that I do have a fully functioning script, but the script is ugly, and I am wondering if there is a way to optimize it.</p>
<p>The script looks to see if I have at least 6 news articles in my database.</p>
<ul>
<li>If I have at least 6 news articles, it branches into a nested if statement.</li>
<li>If the total count is equal to or less than three, it will only show up to three.</li>
<li>If the count is more than 3 it will load the next three.</li>
</ul>
<p>I have a jQuery pagination system, and what I want is for the first three to load, and if there is more than three after, then have the next three load, with a maximum of 6.</p>
<p>What I would like to know is if there is a cleaner way to do what my code does? I am converting my site to a whole new design, and a lot of my sites information is displayed in different ways. What I am not sure how to do, at least not cleanly, is something like accessing all entries in a database, and every three trigger a line break, and after nine trigger another event, etc. Not sure if this makes sense. Anyways here is the script I have currently. </p>
<pre><code><?php
$get_article_count = mysql_query("SELECT count(*) as total FROM table WHERE location='public' AND process='Published'");
$article_count = mysql_fetch_assoc($get_article_count);
if($article_count['total'] <= 6){
?>
<div class="item active">
<div class="row">
<?php
$get_public_articles = mysql_query("SELECT * FROM table WHERE location='public' AND process='Published' ORDER BY articleid DESC LIMIT 0,3");
while($public_articles = mysql_fetch_array($get_public_articles)){
?>
<div class="col-md-4">
<div class="item news-item">
<img alt="" src="upload/blog1.jpg">
<h2><a href="http://www.shiningashes.com/<?=$langauge?>/articles/<?=$public_articles['articleid'];?>"><?=$public_articles['title'];?></a></h2>
<p>
<?php
$pos = str_replace("\\", "", strpos($public_articles['message'], ' ', 170));
if ($pos !== false) {
echo str_replace("\\", "", substr($public_articles['message'], 0, $pos));
}
?>...
</p>
<ul class="blog-tags">
<li><a class="date" href="#"><i class="fa fa-clock-o"></i><?=date('l dS \of F Y', $public_articles['date']);?></a></li>
</ul>
</div>
</div>
<?php
}
?>
</div>
</div>
<div class="item">
<div class="row">
<?php
$get_public_articles = mysql_query("SELECT * FROM sa_news WHERE location='public' AND process='Published' ORDER BY articleid DESC LIMIT 3,6");
while($public_articles = mysql_fetch_array($get_public_articles)){
?>
<div class="col-md-4">
<div class="item news-item">
<img alt="" src="upload/blog1.jpg">
<h2><a href="http://www.shiningashes.com/<?=$langauge?>/articles/<?=$public_articles['articleid'];?>"><?=$public_articles['title'];?></a></h2>
<p>
<?php
$pos = str_replace("\\", "", strpos($public_articles['message'], ' ', 160));
if ($pos !== false) {
echo str_replace("\\", "", substr($public_articles['message'], 0, $pos));
}
?>...
</p>
<ul class="blog-tags">
<li><a class="date" href="#"><i class="fa fa-clock-o"></i><?=date('l dS \of F Y', $public_articles['date']);?></a></li>
</ul>
</div>
</div>
<?php
}
?>
</div>
</div>
<?php
}
?>
</code></pre>
<p>I know that if I put the HTML within <code>echo</code> tags, so it is all PHP, it would be cleaner, but I wanted to get it functioning before converting the whole news "template" to PHP as well.</p>
|
[] |
[
{
"body": "<p>First, putting all HTML into <code>echo</code> does not necessarily make things cleaner. More typically, it makes them full of escaped quotes and difficult to edit in an IDE. I personally only use <code>echo</code> for output that will span less than a full line. I use php tags and heredocs for multiple lines. </p>\n\n<p>A lot of people don't know about heredocs, so I will use them in my example below. The nice thing about heredoc is that it forces you to keep your calculations separate from your outputs, as when I find <code>$date</code> and <code>$message</code> below. That kind of pattern makes for more readable code. However, there are a lot of places where heredoc doesn't make much sense -- usually when you are outputting things conditionally.</p>\n\n<p>If you use heredoc, you must escape literal dollar signs. Keep in mind that the longer the string, the more PHP memory is required for it. Also, it messes up your indentation in PHP because you have to put the final delimiter (\"EOT\" in my example) on its own line. For this reason, I also put the original delimiter starting its own line, even though that's not technically necessary, and I always indent the text inside by at least one indentation level. It just makes it easier to find the beginning of the heredoc. Note that you can also assign your heredoc to a variable etc. instead of echoing it. </p>\n\n<p>Second, I really hope you are getting rid of the use of the deprecated mysql extension during your upgrade. I will use mysqli in my example, but PDO is also a good alternative.</p>\n\n<p>Third, if you want to do something every three rows, all you have to do is save an iterator variable to count for you. You can use the modulus operator (%) to find out if it is multiples of 3 or not.</p>\n\n<p>Fourth, it's pointless to have two copies of the same HTML one right after another, and two copies of nearly-the-same database query. Just do it once. </p>\n\n<pre><code>$i = 0; \n$result = $mysqli->query(\"SELECT * FROM sa_news \n WHERE location='public' AND process='Published' \n ORDER BY articleid DESC \");\n$numrows = $result->num_rows;\nwhile ($public_articles = $result->fetch_assoc()) {\n if($i == 0 || $i%3 == 0) { //beginning of a row\n echo \n<<<EOT\n <div class=\"item active\">\n <div class=\"row\">\nEOT;\n }\n\n $message = '';\n $pos = str_replace(\"\\\\\", \"\", strpos($public_articles['message'], ' ', 170));\n if($pos !== false) {\n $message = str_replace(\"\\\\\", \"\", substr($public_articles['message'], 0, $pos));\n }\n $date = date('l dS \\of F Y', $public_articles['date']);\n\n echo \n<<<EOT\n <div class=\"col-md-4\">\n <div class=\"item news-item\">\n <img alt=\"\" src=\"upload/blog1.jpg\">\n <h2><a href=\"http://www.shiningashes.com/{$language}/articles/{$public_articles['articleid']}\">{$public_articles['title']}</a></h2>\n <p>{$message}</p>\n <ul class=\"blog-tags\">\n <li><a class=\"date\" href=\"#\"><i class=\"fa fa-clock-o\"></i>{$date}</a></li>\n </ul>\n </div>\n </div>\nEOT;\n\n $i++; //the column is now complete\n\n if($i%3 == 0 || $i == $numrows) { //end of a row\n echo \n<<<EOT\n </div>\n </div>\nEOT;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T01:30:45.987",
"Id": "39434",
"ParentId": "39323",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:07:14.780",
"Id": "39323",
"Score": "3",
"Tags": [
"php",
"optimization",
"mysql",
"pagination"
],
"Title": "Searching for news articles in database"
}
|
39323
|
<p>I need to find the end of a loop or the length of the object. Some context on the code:</p>
<p>I obtain the <code>txt</code> var from the DOM (that's the only way I've got by now and can't change it) and it's a formatted JSON. Here's an example of the expected JSON output:</p>
<blockquote>
<p>{"SE DIO AVISO A CENTRAL":true,"OTRO":false,"SE DIO AVISO A SEGURIDAD
CIUDADANA":true,"SIN ACCIÓN":false,"SE DIO AVISO A
AMBULANCIA":false,"SE DIO AVISO A CARABINEROS":true,"SE DIO AVISO A
BOMBEROS":false}</p>
</blockquote>
<p>My idea here is to only show the ones with value <code>true</code>one after the other followed by a comma, but changing that at the end of the loop for a dot. For the moment I've got the commas down but not the dot, which is why I need to know either the length of <code>obj</code> or the end of the <code>$.each()</code> loop. Any improvements on overall code are appreciated.</p>
<pre><code>try{
var obj=jQuery.parseJSON(txt);
$(self).text(" ");
var i = 0;
jQuery.each(obj, function(text, val){
if(val){
if(i == 0){
$(self).append(text);
}else{
$(self).append(", "+text);
}
}
i++;
});
}
catch(e){
}
</code></pre>
|
[] |
[
{
"body": "<p>You can do this with <a href=\"http://api.jquery.com/jquery.map/\" rel=\"nofollow\"><code>jQuery.map</code></a> extremely elegantly as the function allows you to do a filtered map (<code>.map</code> excludes any item when you return <code>null</code> or <code>undefined</code>). As <code>$.map</code> produces an array you can then just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow\"><code>Array.prototype.join</code></a> and get the same output as our original code. If you want to add a period to the string after that then you can check if your string isn't empty, append a period and be on your way.</p>\n\n<pre><code>var text = $.map(obj, function(val, key) { if(val) return key; } ).join(\", \"); //Create an array of an objects keys where its value is truthy. Next, join the keys.\nif(text !== \"\") text += \".\"; // Append a period if not an empty string\n\n$(self).append(text);\n</code></pre>\n\n<p>Also you should reconsider using a try catch block around the JSON parsing as you shouldn't expect that to fail without good reason.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:29:20.473",
"Id": "39327",
"ParentId": "39326",
"Score": "4"
}
},
{
"body": "<p>You are basically mimicking the behavior of join here. Simply collecting the correct values into an array and then joining these values will be simpler.</p>\n\n<p>This is what I would counter-propose:</p>\n\n<pre><code>try{\n var o = jQuery.parseJSON( s ),\n keys = [];\n jQuery.each(o, function(key, value){\n if(value){\n keys.push(key);\n }\n }\n $(self).text( \" \" + keys.join(\",\") + \".\" );\n}\ncatch(e){\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:29:58.340",
"Id": "39328",
"ParentId": "39326",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:13:28.003",
"Id": "39326",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"json"
],
"Title": "Find end of $.each() loop"
}
|
39326
|
<p>I'm kind of new to Python. So, I wonder which method is better to use in a function to find an element in a list.</p>
<p>First:</p>
<pre><code>def search_binary(xs,target):
count = 0
for i in xs:
if i == target:
return count
count = count +1
else:
count = count +1
continue
return -1
</code></pre>
<p>Second:</p>
<pre><code>def search_binary(xs, target):
lb = 0
ub = len(xs)
while True:
if lb == ub:
return -1
mid_index = (lb + ub) // 2
item_at_mid = xs[mid_index]
if item_at_mid == target:
return mid_index
if item_at_mid < target:
lb = mid_index + 1
else:
ub = mid_index
</code></pre>
|
[] |
[
{
"body": "<p>If your list is sorted you can use binary search (your second code), and it will be faster for large lists, but if it's unsorted you'll have to keep to linear search. The Python library provides fast implementation of both methods, so you really don't need to roll your own:</p>\n\n<pre><code>>>> a = range(10)\n\n>>> a.index(4) # linear search\n4\n\n>>> import bisect\n>>> idx = bisect.bisect(a, 4) # binary search\n>>> if a[idx-1] == 4:\n... print idx - 1\n... else:\n... raise ValueError('item not in list')\n... \n4\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:30:12.877",
"Id": "66004",
"Score": "0",
"body": "For the curious, I can confirm that sorting and then using a binary search _is not_ faster"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:45:21.827",
"Id": "66016",
"Score": "2",
"body": "That depends on how much searching you have to do... Sorting a list of `n` items takes `O(n log n)` time, but then you can do a search in `O(log n)` time. So if you have to search for `m` items, sorting then searching will take time `O((m+n) log n)`, while the linear search takes time `O(mn)`. If you have to search for a single item then it doesn't pay off to first sort, if you have a million, then it may."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T21:06:54.533",
"Id": "39331",
"ParentId": "39329",
"Score": "4"
}
},
{
"body": "<p>Bisect is the 'right' answer for serious applications where speed matters. It sounded to me like you're asking a style question. On that assumption:</p>\n\n<pre><code>def search_binary(xs,target): # enumerate generates the indices for you\n for count, val in enumerate(xs):\n if val == target: \n return count # no need to explicitly continue either\n return -1\n</code></pre>\n\n<p>Is the simplest loop style version. You could write nearly the same thing as:</p>\n\n<pre><code>def search_binary_with_comprehension (xs, target):\n return [ count for count, val in enumerate(xs) if val == target]\n # list comprehensions ftw!\n</code></pre>\n\n<p>which would return a list of all the indices in the list with the target val, and an empty list if the target was not found</p>\n\n<p>For the simplest case - just finding an object in a list, the <strong>real</strong> python way to do it is:</p>\n\n<pre><code>found_index = xs.index(target) # assuming xs is a list or tuple\n</code></pre>\n\n<p>which will return the index if it can, and raise a ValueError if the target is not present, or</p>\n\n<pre><code>target in xs\n</code></pre>\n\n<p>which will be true if target is anywhere in xs and false if not:</p>\n\n<pre><code>if not target in xs:\n print 'target is not in list!'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T23:41:11.263",
"Id": "39343",
"ParentId": "39329",
"Score": "3"
}
},
{
"body": "<p>In your first piece of code...</p>\n\n<pre><code>count = count + 1\n</code></pre>\n\n<p>can be rewritten as:</p>\n\n<pre><code>count += 1\n</code></pre>\n\n<p>Secondly, putting</p>\n\n<pre><code>count = count + 1\n</code></pre>\n\n<p>under a return statement is silly. The return statements boots you out of the function meaning that code will never be run.</p>\n\n<p>Finally, adding</p>\n\n<pre><code>continue\n</code></pre>\n\n<p>at the end of a loop is also a bit silly. Your loop is going to reiterate regardless of whether you force it along with a continue or not.</p>\n\n<p>To answer your question, the first piece of code is more pythonic in nature. (Readability)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T16:27:56.780",
"Id": "455678",
"Score": "0",
"body": "I'm sorry but `count += 1` doesn't work in python :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T14:17:13.340",
"Id": "39968",
"ParentId": "39329",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:52:29.913",
"Id": "39329",
"Score": "7",
"Tags": [
"python",
"beginner",
"binary-search"
],
"Title": "Finding an element in a list"
}
|
39329
|
<p>This compiler, implemented in C++, takes brainfuck code and produces a valid (but still obfuscated) C program, which in turn can be compiled to a native binary.</p>
<p>Expected usage is as follows:</p>
<ol>
<li><p>Build the compiler</p>
<pre><code>$ c++ -o bfc bfc.cpp
</code></pre></li>
<li><p>Compile a brainfuck program (<a href="https://codereview.stackexchange.com/a/39252/9357">example</a>) to C</p>
<pre><code>$ ./bfc ascii.bf
</code></pre></li>
<li><p>Compile the resulting C program to an executable.</p>
<pre><code>$ cc -g -O0 -o ascii ascii.bf.c
</code></pre></li>
<li><p>Run the executable natively.</p>
<pre><code>$ ./ascii
</code></pre>
<p>Or, you can also run it in a debugger. As long as you compiled with debugging symbols included and without optimizations, you should be able to step through the brainfuck source code line by line.</p>
<pre><code>$ gdb ascii
[...]
(gdb) break ascii.bf:1
Breakpoint 1 at 0x1000010fc: file ascii.bf, line 1.
(gdb) run
[...]
Breakpoint 1, main (argc=1, argv=0x7fff5fbffbd0) at ascii2.bf:1
1 [-][
(gdb) break ascii.bf:66
Breakpoint 2 at 0x1000031c3: file ascii.bf, line 66.
(gdb) cont
Continuing.
Breakpoint 2, main (argc=1, argv=0x7fff5fbffbd0) at ascii.bf:66
66 >>>>> >>>>> >>> . (c_ascii)
(gdb) display m.ptr
1: m.ptr = 4
Current language: auto; currently minimal
(gdb) display /d m.mem[0] @ 32
2: /d m.mem[0] @ 32 = {0, 58, 32, 10, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 58, 48, 1, 0, 0, 0, 58, 48, 1, 0, 0, 0, 58, 48, 0, 0}
(gdb) display /d m.mem[m.ptr]
3: /d m.mem[m.ptr] = 0
</code></pre></li>
</ol>
<p>I'd like to know:</p>
<ol>
<li>How well does this technique work for debuggers other than GDB?</li>
<li>Is there anything I should do to make either the compiler source code or the generated output more readable?</li>
<li>How should I improve the error handling?</li>
<li>Are there any other improvements you might suggest?</li>
</ol>
<p></p>
<pre><code>#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
static const char BOILERPLATE_HEAD[] = "\
#include <stdio.h>\n\
#include <stdlib.h>\n\
#include <strings.h>\n\
\n\
typedef unsigned char bf_mem_t;\n\
\n\
struct machine_state {\n\
int ptr;\n\
int size;\n\
bf_mem_t *mem;\n\
};\n\
\n\
void error(int line, struct machine_state *m) __attribute__((noreturn));\n\
void error(int line, struct machine_state *m) {\n\
abort();\n\
}\n\
\n\
int init_machine(struct machine_state *m) {\n\
m->ptr = 0;\n\
m->size = 8;\n\
m->mem = calloc(m->size, sizeof(bf_mem_t));\n\
return 0 != m->mem;\n\
}\n\
\n\
int realloc_machine(int line, struct machine_state *m, int min_size) {\n\
int new_size = m->size;\n\
do {\n\
new_size <<= 1;\n\
} while (new_size < min_size);\n\
if (NULL == (m->mem = realloc(m->mem, new_size))) {\n\
return 0;\n\
}\n\
bzero(m->mem + m->size, new_size - m->size);\n\
m->size = new_size;\n\
return 1;\n\
}\n\
\n\
void advance(int line, struct machine_state *m, int change) {\n\
m->ptr += change;\n\
}\n\
\n\
int ensure(int line, struct machine_state *m) {\n\
if (m->ptr < 0) {\n\
return 0;\n\
}\n\
if (m->ptr >= m->size && !realloc_machine(line, m, m->ptr)) {\n\
return 0;\n\
}\n\
return 1;\n\
}\n\
\n\
int incr(int line, struct machine_state *m, int change) {\n\
if (!ensure(line, m)) {\n\
return 0;\n\
}\n\
m->mem[m->ptr] += change;\n\
return 1;\n\
}\n\
\n\
bf_mem_t mem(int line, struct machine_state *m) {\n\
if (m->ptr < 0) {\n\
error(line, m);\n\
} else if (m->ptr >= m->size) {\n\
return 0;\n\
} else {\n\
return m->mem[m->ptr];\n\
}\n\
}\n\
\n\
/* Only useful as a possible debugging breakpoint */\n\
struct machine_state *beginwhile(struct machine_state *m) {\n\
return m;\n\
}\n\
\n\
/* Only useful as a possible debugging breakpoint */\n\
struct machine_state *endwhile(struct machine_state *m) {\n\
return m;\n\
}\n\
\n\
int input(int line, struct machine_state *m) {\n\
if (!ensure(line, m)) {\n\
return 0;\n\
}\n\
int c = getchar();\n\
if (-1 == c) {\n\
return 0;\n\
} else {\n\
m->mem[m->ptr] = c;\n\
return 1;\n\
}\n\
}\n\
\n\
void output(int line, struct machine_state *m) {\n\
putchar(mem(line, m));\n\
}\n\
void comment(int line, struct machine_state *m, const char *comment) {\n\
return;\n\
fprintf(stderr, \"%d %s\", line, comment);\n\
}\n\
\n\
#define L advance(__LINE__, &m, -1);\n\
#define R advance(__LINE__, &m, +1);\n\
#define M if (!incr(__LINE__, &m, -1)) error(__LINE__, &m);\n\
#define P if (!incr(__LINE__, &m, +1)) error(__LINE__, &m);\n\
#define W while(mem(__LINE__, beginwhile(&m)))\n\
#define E endwhile(&m);\n\
#define I if (!input(__LINE__, &m)) error(__LINE__, &m);\n\
#define O output(__LINE__, &m);\n\
#define C(x) comment(__LINE__, &m, (x));\n\
\n\
\n\
int main(int argc, char *argv[]) {\n\
struct machine_state m;\n\
init_machine(&m);\n"
"#line 1 ";
static const char BOILERPLATE_TAIL[] = "}\n";
struct ParserState {
std::string comment;
};
std::string &c_escape_string(std::string &comment) {
std::string::size_type i = 0;
while (std::string::npos != (i = comment.find_first_of("\\\a\b\f\n\r\t\v\"", i))) {
switch (comment[i]) {
case '\\': comment.replace(i, 0, "\\"); break;
case '\a': comment.replace(i, 1, "\\a"); break;
case '\b': comment.replace(i, 1, "\\b"); break;
case '\f': comment.replace(i, 1, "\\f"); break;
case '\n': comment.replace(i, 1, "\\n"); break;
case '\r': comment.replace(i, 1, "\\r"); break;
case '\t': comment.replace(i, 1, "\\t"); break;
case '\v': comment.replace(i, 1, "\\v"); break;
default: comment.replace(i, 0, "\\");
}
i += 2;
}
return comment.insert(0, "\"").append("\"");
}
std::ostream &emit_boilerplate_head(std::ostream &out, const std::string &filename) {
out << BOILERPLATE_HEAD;
if (!filename.empty()) {
std::string fn(filename);
out << c_escape_string(fn);
}
return out << std::endl;
}
std::ostream &emit_boilerplate_tail(std::ostream &out) {
return out << BOILERPLATE_TAIL;
}
std::ostream &emit_comment(ParserState &state, std::ostream &out) {
std::string leading_whitespace, trailing_whitespace;
std::string::size_type pos;
if (std::string::npos != (pos = state.comment.find_first_not_of(" \f\n\r\t\v"))) {
leading_whitespace = state.comment.substr(0, pos);
state.comment = state.comment.substr(pos);
}
if (std::string::npos != (pos = state.comment.find_last_not_of(" \f\n\r\t\v"))) {
trailing_whitespace = state.comment.substr(pos + 1);
state.comment.resize(pos + 1);
}
out << leading_whitespace;
if (!state.comment.empty()) {
out << "C(" << c_escape_string(state.comment) << ")";
state.comment.clear();
}
out << trailing_whitespace;
return out;
}
std::ostream &emit_instruction(ParserState &state, std::ostream &out, char instruction) {
emit_comment(state, out);
if ('W' == instruction) {
out << "W{"; // Exception for readability
} else if ('E' == instruction) {
out << "E}"; // Exception for readability
} else {
out << instruction << ' ';
}
return out;
}
/* Try hard to preserve whitespace, especially line breaks, so that debuggers
can deduce the right line numbers. */
std::ostream &emit_whitespace(ParserState &state, std::ostream &out, char c) {
if (state.comment.empty()) {
out << c;
} else {
state.comment += c;
}
if (c == '\n' || c == '\r') {
emit_comment(state, out);
}
return out;
}
std::ostream &compile(std::istream &in, std::ostream &out) {
ParserState state;
char c;
while (in.get(c)) {
if (isspace(c)) {
emit_whitespace(state, out, c);
} else switch (c) {
// Operations and their mnemonics
case '<': emit_instruction(state, out, 'L'); break; // Left
case '>': emit_instruction(state, out, 'R'); break; // Right
case '-': emit_instruction(state, out, 'M'); break; // Minus
case '+': emit_instruction(state, out, 'P'); break; // Plus
case '[': emit_instruction(state, out, 'W'); break; // While
case ']': emit_instruction(state, out, 'E'); break; // End
case ',': emit_instruction(state, out, 'I'); break; // Input
case '.': emit_instruction(state, out, 'O'); break; // Output
default: state.comment += c;
}
}
emit_comment(state, out);
return out;
}
int main(int argc, char *argv[]) {
std::istream *in = &std::cin;
std::ostream *out = &std::cout;
std::ifstream infile;
std::ofstream outfile;
std::string filename;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] && argv[i][0] != '-') {
filename = argv[i];
infile.open(filename);
outfile.open(filename + ".c");
in = &infile;
out = &outfile;
break;
}
}
emit_boilerplate_head(*out, filename);
compile(*in, *out);
emit_boilerplate_tail(*out);
*out << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:38:05.880",
"Id": "65882",
"Score": "0",
"body": "I might be missing something, but why are you methods all return a `std::ostream` reference? I guess it could facilitate method chaining but it's not really used as far as I can see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:58:01.187",
"Id": "65886",
"Score": "0",
"body": "@ChrisWue That was the intention, but it didn't turn out to be that useful in practice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:38:47.983",
"Id": "66233",
"Score": "0",
"body": "Would that not be a translator not a compiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:39:03.973",
"Id": "66240",
"Score": "0",
"body": "@LokiAstari You could call it a translator. However, it fits [Wikipedia](http://en.wikipedia.org/wiki/Compiler)'s definition of a _compiler_ as \"A compiler is a computer program (or set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language, often having a binary form known as object code).\""
}
] |
[
{
"body": "<p>As far as I can understand</p>\n\n<pre><code>default: comment.replace(i, 0, \"\\\\\");\n</code></pre>\n\n<p>makes</p>\n\n<pre><code>case '\\\\': comment.replace(i, 0, \"\\\\\"); break;\n</code></pre>\n\n<p>useless.</p>\n\n<p>Edit to add another comment :</p>\n\n<p>Please activate all warnings on your code on one hand and on the generated code on the other hand. I think that :</p>\n\n<pre><code>void comment(int line, struct machine_state *m, const char *comment) {\\n\\\n return;\\n\\\n fprintf(stderr, \\\"%d %s\\\", line, comment);\\n\\\n}\\n\\\n</code></pre>\n\n<p>shoud eventually warn you about unreachable code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:34:23.210",
"Id": "40264",
"ParentId": "39330",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40264",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:57:14.837",
"Id": "39330",
"Score": "16",
"Tags": [
"c++",
"c",
"error-handling",
"brainfuck",
"portability"
],
"Title": "Brainfuck-to-C compiler written in C++"
}
|
39330
|
<p>I'm just getting into testing and wanted to see if someone can tell me if I'm writing tests correctly. I'm using C#, NUnit, & Should.</p>
<p>This is the class I'm testing:</p>
<pre><code> using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
Using VM.Models.Common;
namespace Vm.Models.CustomerNS
{
public class Customer
{
// ReSharper disable once InconsistentNaming
public int ID { get; set; }
public List<Address> Locations { get; set; }
public List<User> Users { get; set; }
public List<BuyerNum> BuyerNumbers { get; set; }
public Dictionary<string, string> VehicleList { get; set; }
public List<Contact> Contacts { get; set; }
public string Name { get; set; }
public Customer()
{
Locations = new List<Address>();
Users = new List<User>();
BuyerNumbers = new List<BuyerNum>();
Contacts = new List<Contact>();
VehicleList = new Dictionary<string,string>();
}
public void AddLocation(AddressType addtype, string addressName, string streetAddress, string city, string state, string zip, string country)
{
var addressId = 0;
var lastOrDefault = Locations.LastOrDefault();
if (lastOrDefault != null) addressId = lastOrDefault.AddressId + 1;
Address newAddress = new Address
{
AddressId = addressId,
AddressName = addressName,
AddressType = addtype,
City = city,
State = state
};
if (streetAddress != null) newAddress.StreetAddress = streetAddress;
if (zip != null) newAddress.Zip = zip;
Locations.Add(newAddress);
}
public void RemoveLocation(int addressId)
{
Debug.Assert(Locations != null, "Locations != null");
var addressid = Locations.Where(x => x.AddressId == addressId);
var enumerable = addressid as IList<Address> ?? addressid.ToList();
if (enumerable.Count() != 1) { throw new InvalidOperationException("Cannot Delete"); }
Locations.Remove(enumerable.First());
}
public void ModifyLocation(int addressId, AddressType addtype, string addressName, string streetAddress, string city, string state, string zip, string country)
{
var addressid = Locations.Where(x => x.AddressId == addressId);
var enumerable = addressid as Address[] ?? addressid.ToArray();
if (enumerable.Count() != 1) { throw new InvalidOperationException("Cannot Delete"); }
Locations.Remove(enumerable.First());
}
public Address GetLocation(int addressId)
{
return Locations.First(x => x.AddressId == addressId);
}
public List<Address> GetAllLocations()
{
return Locations;
}
}
}
</code></pre>
<p>Testing Class</p>
<pre><code> using System.Linq;
using Vm.Models.Common;
using VM.Models.CustomerNS;
using NUnit.Framework;
using Should;
// ReSharper disable once CheckNamespace
namespace vm.Models.CustomerNS.Tests
{
[TestFixture()]
public class CustomerTests
{
[Test()]
public void CustomerTest()
{
var customerObject = new Customer() { Name = "Hello World!!" };
customerObject.ShouldNotBeNull();
Assert.AreEqual(customerObject.Name, "Hello World!!");
}
[Test()]
public void AddLocationTest()
{
var customerObject = new Customer() { Name = "Hello World!!" };
customerObject.AddLocation(AddressType.Business, "Hello Location", "123 Street Name", "Hello City", "HS", "10001", "US");
customerObject.Locations.First().ShouldNotBeNull();
Assert.AreEqual(customerObject.Locations.First().City, "Hello City");
}
[Test()]
public void RemoveLocationTest()
{
var customerObject = new Customer() { Name = "Hello World!!" };
customerObject = GenerateMultipleLocations(5, customerObject);
var inintialCount = customerObject.Locations.Count;
var custObjCopy = customerObject.Locations.First();
var thirdlocation = customerObject.Locations[3];
customerObject.RemoveLocation(1);
customerObject.Locations.Count.ShouldEqual(inintialCount - 1);
customerObject.Locations.First().ShouldEqual(custObjCopy);
customerObject.Locations[3].ShouldNotEqual(thirdlocation);
}
private Customer GenerateMultipleLocations(int p, Customer customer)
{
int i = 0;
while (i < p)
{
customer.AddLocation(AddressType.Business, EfficientlyLazy.IdentityGenerator.Generator.GenerateName().First, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().AddressLine, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().StateAbbreviation, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().ZipCode, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City);
i++;
}
return customer;
}
[Test()]
public void ModifyLocationTest()
{
var customerObject = new Customer() { Name = "Hello World!!" };
customerObject = GenerateMultipleLocations(5, customerObject);
var inintialCount = customerObject.Locations.Count;
var custObjCopy = customerObject.Locations.First();
var thirdlocation = customerObject.Locations[3];
customerObject.Locations[3].AddressId.ShouldEqual(3);
customerObject.ModifyLocation(3, AddressType.Business, EfficientlyLazy.IdentityGenerator.Generator.GenerateName().First, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().AddressLine, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().StateAbbreviation, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().ZipCode, EfficientlyLazy.IdentityGenerator.Generator.GenerateAddress().City);
thirdlocation.ShouldNotEqual(customerObject.Locations[3]);
}
[Test()]
public void GetLocationTest()
{
Assert.Fail();
}
[Test()]
public void GetAllLocationsTest()
{
Assert.Fail();
}
}
}
</code></pre>
<p>PS: I realize I haven't tested the bottom 2 methods.</p>
|
[] |
[
{
"body": "<p>My first observations is: use injection! </p>\n\n<p>for example: Instead of passing in<code>AddressType addtype, string addressName, string streetAddress, string city, string state, string zip, string country</code> into <code>AddLocation</code>, expect an <code>Address</code> instance. This simplifies the code greatly (a method should preferably have max 2 parameters), and in the future if you need functionality in the <code>Address</code> class, you will be able to pull an interface and mock the required return from the functionality.</p>\n\n<p>I'm not sure where the <code>ShouldNotBeNull</code>, <code>ShouldNotBeEqual</code>, and <code>ShouldBeEqual</code> methods are coming from. While I understand what you are trying to do with them, I find them distracting from reading the tests. Maybe its just my brain trained to be looking for <code>Assert</code> for the checking part, I don't know, but on initial read through, I found it difficult to follow.</p>\n\n<p>For your test when changing things, I always add an <code>Assert</code> on the base case.</p>\n\n<pre><code>private void TestSomething()\n{\n var sut = new List<string>\n {\n \"one\",\n }\n\n Assert.That(sut.Count, Is.EqalTo(1));\n\n sut.Add(\"Two\");\n\n Assert.That(sut.Count, Is.EqualTo(2));\n}\n</code></pre>\n\n<p>I always name my class being tested sut (System Under Test). This allows anybody reading it to easily identify which class you are actually testing.</p>\n\n<p>I would also rename your test methods. Having <code>Test</code> in the name is a little redundant, seems how this is a test fixture. I like having my method names reflect what is being tested and what the expected result is:</p>\n\n<pre><code>[Test]\npublic void CallingAddLocationWithValidDataShouldAddLocationToCustomer()\n{\n // Code goes here\n}\n</code></pre>\n\n<p><code>GenerateMultipleLocations</code> does not have to return the <code>Customer</code> instance because it is being passed in as a ref automatically. Any changes made in the method will be reflected in the class in the original method.</p>\n\n<p>As far as testing goes, this is much better than the mess I created when I first started. Keep working at it, eventually it will be very easy to see and write tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:19:38.060",
"Id": "65902",
"Score": "0",
"body": "Hi Jeff, thanks for the suggestions. All the \"shoulds\" are coming from Should, which is an assertion library, it was used in test for a repository library, so I just decided to keep it, seems very simple :) The test boilerplate and method names are from test generator for Visual Studio, I'll look into renaming them though"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T22:50:13.943",
"Id": "39341",
"ParentId": "39336",
"Score": "4"
}
},
{
"body": "<p>I'm a little more concerned about the implementation class (as opposed to the testing class). It exposes <code>List<T></code> and <code>Dictionary<T,U></code> properties publicly, assigns them in the constructor but also allows them to be set via the property. Something smells, but I can't speak to it not knowing the full design. However, if you can, I'd recommend developing to interfaces, <code>IList<T></code> and <code>IDictionary<T,U></code> instead and not allowing setters on the properties. Here's what I'd code up:</p>\n\n<pre><code>namespace Vm.Models.CustomerNS\n{\n using System;\n using System.Collections.Generic;\n using System.Diagnostics;\n using System.Linq;\n\n using Vm.Models.Common;\n\n public class Customer\n {\n private readonly IList<Address> locations = new List<Address>();\n\n private readonly IList<User> users = new List<User>();\n\n private readonly IList<BuyerNum> buyerNumbers = new List<BuyerNum>();\n\n private readonly IList<Contact> contacts = new List<Contact>();\n\n private readonly IDictionary<string, string> vehicleList = new Dictionary<string, string>();\n\n public IList<BuyerNum> BuyerNumbers\n {\n get\n {\n return this.buyerNumbers;\n }\n }\n\n public IList<Contact> Contacts\n {\n get\n {\n return this.contacts;\n }\n }\n\n // ReSharper disable once InconsistentNaming\n public int ID\n {\n get;\n\n set;\n }\n\n public IList<Address> Locations\n {\n get\n {\n return this.locations;\n }\n }\n\n public string Name\n {\n get;\n\n set;\n }\n\n public IList<User> Users\n {\n get\n {\n return this.users;\n }\n }\n\n public IDictionary<string, string> VehicleList\n {\n get\n {\n return this.vehicleList;\n }\n }\n\n public void AddLocation(\n AddressType addtype,\n string addressName,\n string streetAddress,\n string city,\n string state,\n string zip,\n string country)\n {\n var lastOrDefault = this.Locations.LastOrDefault();\n var newAddress = new Address\n {\n AddressId = lastOrDefault == null ? 0 : lastOrDefault.AddressId + 1,\n AddressName = addressName,\n AddressType = addtype,\n City = city,\n State = state\n };\n\n if (streetAddress != null)\n {\n newAddress.StreetAddress = streetAddress;\n }\n\n if (zip != null)\n {\n newAddress.Zip = zip;\n }\n\n this.Locations.Add(newAddress);\n }\n\n public IList<Address> GetAllLocations()\n {\n return this.Locations;\n }\n\n public Address GetLocation(int addressId)\n {\n return this.Locations.First(x => x.AddressId == addressId);\n }\n\n public void ModifyLocation(\n int addressId,\n AddressType addtype,\n string addressName,\n string streetAddress,\n string city,\n string state,\n string zip,\n string country)\n {\n var addressid = this.Locations.Where(x => x.AddressId == addressId).ToList();\n\n if (addressid.Count() != 1)\n {\n throw new InvalidOperationException(\"Cannot Delete\");\n }\n\n this.Locations.Remove(addressid.First());\n }\n\n public void RemoveLocation(int addressId)\n {\n Debug.Assert(this.Locations != null, \"Locations != null\");\n\n var addressid = this.Locations.Where(x => x.AddressId == addressId).ToList();\n\n if (addressid.Count() != 1)\n {\n throw new InvalidOperationException(\"Cannot Delete\");\n }\n\n this.Locations.Remove(addressid.First());\n }\n }\n}\n</code></pre>\n\n<p>Onto the unit test class. There are a number of stylistic issues I'd probably change, but I think only two real little testing bits that were off:</p>\n\n<p>In method <code>ModifyLocationTest</code>, you get the location count, but it would seem prudent to <code>Assert</code> it:</p>\n\n<pre><code>GenerateMultipleLocations(5, customerObject);\n\nvar initialCount = customerObject.Locations.Count;\n\nAssert.AreEqual(initialCount, 5);\n</code></pre>\n\n<p>And method <code>GenerateMultipleLocations</code> can be made <code>static</code>.</p>\n\n<p>Back to the issue of the initial classes - if you can create <code>interface</code>s for them, it would make dependency injection and mocking easier for unit testing. I can expound on that if you'd like, but I suggest reading up on those first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:16:24.477",
"Id": "65881",
"Score": "0",
"body": "`ModifyLocation` only needs the `addressId` - no need to pass in all the other stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:11:41.233",
"Id": "65900",
"Score": "0",
"body": "Hi Jesse, thank you very much for your answer. This was actually a refactor of a class, and I haven't gotten around to making the props private yet, I was actually planning to stick all access logic into the crud methods. I'm actually trying to read up on DI currently, my next goal is to learn Ninject"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:22:59.260",
"Id": "65903",
"Score": "0",
"body": "@Chris my logic for that was that the modified info would be passed into the method, and the method then modifies the object. Would there be an easier/better way to do this?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T23:41:36.230",
"Id": "39344",
"ParentId": "39336",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39344",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T21:52:45.757",
"Id": "39336",
"Score": "8",
"Tags": [
"c#",
"unit-testing",
"nunit"
],
"Title": "Testing classes"
}
|
39336
|
<p>I am learning Java as my first programming language and have written a bit of code. I would love to read expert reviews on this code and suggestions to improve right from naming conventions to logic. Please let me know if there is any kind of mistake.</p>
<pre><code>public class Sudoku {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int[][] array = { { 0, 2, 0, 5, 0, 0, 0, 9, 0 },
{ 5, 0, 0, 0, 7, 9, 0, 0, 4 },
{ 3, 0, 0, 0, 1, 0, 0, 0, 0 },
{ 6, 0, 0, 0, 0, 0, 8, 0, 7 },
{ 0, 7, 5, 0, 2, 0, 0, 1, 0 },
{ 0, 1, 0, 0, 0, 0, 4, 0, 0 },
{ 0, 0, 0, 3, 0, 8, 9, 0, 2 },
{ 7, 0, 0, 0, 6, 0, 0, 4, 0 },
{ 0, 3, 0, 2, 0, 0, 1, 0, 0 } };
solve(array);
System.out.println("Solution is ");
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
System.out.print(" " + array[row][col] + " ");
}
System.out.println();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Time taken (in MilliSeconds)= " + totalTime);
}
public static boolean solve(int[][] array) {
if (isSum45(array)) {
return true;
}
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (array[row][col] == 0) {
for (int num = 1; num <= 9; num++) {
if (noConflict(array, row, col, num)) {
array[row][col] = num;
if (solve(array)) {
return true;
}
}
array[row][col] = 0;
}
return false;
}
}
}
return false;
}
// This method edited is after taking suggestions from this forum
public static boolean noConflict(int[][] array, int row, int col, int num) {
for (int k = 0; k < 9; k++) {
if (array[row][k] == num) {
return false;
}
if (array[k][col] == num) {
return false;
}
}
int m = row - (row % 3);
int n = col - (col % 3);
for (int p = m; p < m + 3; p++) {
for (int q = n; q < n + 3; q++) {
if (array[p][q] == num) {
return false;
}
}
}
return true;
}
public static boolean isSum45(int[][] array) {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
int sum = 0;
int m = row - (row % 3);
int n = col - (col % 3);
for (int p = m; p < m + 3; p++) {
for (int q = n; q < n + 3; q++) {
sum = sum + array[p][q];
}
}
if (sum != 45) {
return false;
}
}
}
return true;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T22:26:36.920",
"Id": "65846",
"Score": "1",
"body": "Your noConflict is a waste of processor. You should be looking only for the number you try to set, so instead of: add to list every number in row and column, check if num is in the list, return; you can only do: check if number is in row or column, return when found. It will be much faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T22:31:16.453",
"Id": "65847",
"Score": "0",
"body": "@fernando.reyes I couldn't get your point correctly. What if the number is in the current grid? With that in mind I wrote like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T22:55:16.450",
"Id": "65849",
"Score": "0",
"body": "I miss that part, let's rephrase it. The first `for` with two ifs, instead of adding everything to the list, `if (array[row][k] == num ) return false;` and that saves some loop cycles"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T12:21:01.430",
"Id": "65898",
"Score": "0",
"body": "@fernando.reyes I changed the code as suggested by you. Thanks once again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T16:20:48.220",
"Id": "65935",
"Score": "0",
"body": "Sudoku was the topic of a recent [WeekEnd Challenge](http://codereview.stackexchange.com/search?q=[weekend-challenge]+sudoku) here on CodeReview. you should consider scanning those answers for ideas. Additionally, there is a relatively comprehensive Java solution on the [CodeReview GitHub](https://github.com/CodeReviewCommunity/Java-Sudoku-Solver) which may provide some inspiration."
}
] |
[
{
"body": "<p>Overall, this is pretty good code for a beginner's solution to a relatively complex problem.</p>\n\n<p>But your code <em>does</em> have me a little lost. For one, I'm not quite sure why you're using recursion here. It seems like that will be a <em>lot</em> more memory intensive than it needs to be for a straightforward problem. It also confused me for a good ten minutes why you were checking for <code>isSum45</code> to return that the problem is solved, when the sum for the entire board is actually 405.</p>\n\n<p>I would rewrite this as an iterative solution rather than a recursive solution. I think the recursion adds a lot of unnecessary complexity to the code and flow. I don't have the time at the moment to rewrite it as such, so I'll just give some other general comments on your code.</p>\n\n<pre><code>solve(array);\nSystem.out.println(\"Solution is \");\nfor (int row = 0; row < 9; row++) {\n for (int col = 0; col < 9; col++) {\n System.out.print(\" \" + array[row][col] + \" \");\n }\n System.out.println();\n}\n</code></pre>\n\n<p>I'm not a big fan of the above implementation because it relies on the <code>solve()</code> method modifying the original array in place. It also makes your paradigm of returning a <code>boolean</code> from the <code>solve()</code> method irrelevant; you never compare or check for it. I think it would be a better design if you <em>preserve</em> the original board and create a new <code>int[][] solved</code> variable which you return from the method.</p>\n\n<pre><code>for (int row = 0; row < 9; row++) {\n for (int col = 0; col < 9; col++) {\n if (array[row][col] == 0) {\n for (int num = 1; num <= 9; num++) {\n if (noConflict(array, row, col, num)) {\n array[row][col] = num;\n if (solve(array)) {\n return true;\n }\n }\n array[row][col] = 0;\n }\n return false;\n }\n }\n}\n</code></pre>\n\n<p>On a positive note, I really like that you named your loop variables <code>row</code> and <code>col</code> versus <code>i</code> and <code>j</code> as so many people do. It makes your code much more readable. But one of the principles of good code design is to avoid this kind of intense nesting as much as possible. You can do this like the following:</p>\n\n<pre><code>for(int row = 0; row < array.length; row++) {\n for(int column = 0; column < array[row].length; column++) {\n if(array[row][column] != 0) continue;\n for(int num = 1; num <= 9; num++) {\n if(!noConflict(array, row, column, num)) continue;\n array[row][column] = num;\n if(solve(array)) return true;\n array[row][column] = 0\n }\n return false;\n }\n}\n</code></pre>\n\n<p>This makes your code a bit less complex and a bit more readable. I completely avoid your <code>if(solve(array))</code> block by simply returning the boolean directly from the recursive method call (<strong>EDITED</strong>: As David Harkness says in the comments below, this actually changes how the method functions, so I've removed that bit.). Also note that it my loops I compare <code>row</code> and <code>column</code> to <code>array.length</code> and <code>array[row].length</code>, respectively. This isn't a huge deal if you always know you're going to be handling boards which are 9x9, however when you're designing code you should always try to make your code as flexible as possible. The more flexible it is and the more scenarios it can handle, the more powerful it is.</p>\n\n<pre><code>public static boolean noConflict(int[][] array, int row, int col, int num) {\n</code></pre>\n\n<p>This is just general nitpicking, but you should only expose methods as <code>public</code> which actually need to be <code>public</code>. The <code>solve</code> method makes sense as a <code>public</code> method because it's the part of the API that you will want to use in other parts of the application. This method, however, is purely internal and thus should be <code>private</code>. Also, method names should pretty much always be verbs or verb phrases. I might rename this method to something like <code>noConflictExists</code> or <code>isNoConflict</code>. Actually, because of the nature of how I rewrote your loops above, I would change it to <code>conflictExists</code> or <code>isConflict</code> that way my usage of it is more intuitive. These notes also apply to your <code>isSum45</code> method, which is <code>public</code> and might use a more intuitive name for code readability.</p>\n\n<p>Also, in those two methods, what happened to your beautiful variable names?!? Why did you suddenly move to using single letters instead of something more descriptive?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:40:31.210",
"Id": "65924",
"Score": "0",
"body": "Thanks for your appreciation and review. Do you really think that the sudoku can be solved based on your rewrite of solve()? Please check once and let me know if I am wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:51:17.447",
"Id": "65927",
"Score": "0",
"body": "The isSum45() is actually the base case for the recursive backtracking algorithm. This condition will be met only when the entire board is filled with the correct numbers i.e. 1 to 9 whose sum is actually 45. The method checks whether the sub grids follow the rule of the game or not. Hope you got my point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:56:10.097",
"Id": "65929",
"Score": "0",
"body": "@Phoenix Sure. My rewrite doesn't actually change any of the functionality of your code, just the readability by reducing the number of nestings. I'm sure your method does work great for the recursion. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:45:04.167",
"Id": "65983",
"Score": "1",
"body": "You can't simply return the result of the recursive call to `solve`. If the result is `false` you must try the next number, or it will give up on the first incorrect guess. While I've found the recursive brute-force approach to be the simplest to implement and understand, you do make other good points so +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:47:07.693",
"Id": "65984",
"Score": "0",
"body": "@DavidHarkness Ah, good point. When skimming it, my brain only processed the `if(true) return true` style. Will fix. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:16:10.073",
"Id": "66009",
"Score": "0",
"body": "@Jeff Gohlke Please try fixing the suggestions. It doesn't solve sudoku. I tried today too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:22:55.983",
"Id": "66010",
"Score": "0",
"body": "@JeffGohlke Add array[row][column] = 0; immediately after if (solve(array)). Then it will be fixed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:34:31.987",
"Id": "66114",
"Score": "0",
"body": "@Phoenix That was something I was confused by as well. Why are you setting the solution to whatever number, then unsetting it again? It seems like another example of how your design is quite convoluted. In any case, I added the line. My apologies for missing it while skimming your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T04:38:49.003",
"Id": "66264",
"Score": "0",
"body": "@JeffGohlke Thanks a lot for your insightful review. The solution that I have arrived at is actually the simplest of all, I think. May be you didn't spend time why that zero being assigned after that if() clause. Spend some time. If you find an easier solution than this, kindly let me know as the title of this post also reflects the same. Thanks once again."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:53:10.297",
"Id": "39392",
"ParentId": "39337",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T22:01:11.553",
"Id": "39337",
"Score": "7",
"Tags": [
"java",
"beginner",
"recursion",
"sudoku"
],
"Title": "Alternative methods of solving Sudoku"
}
|
39337
|
<p>I have a Backbone.Collection which has some models in it. Each model has a boolean property called 'special.' Only one model should be special at any given time.</p>
<p>I've got the following to enforce this, but I'm wondering if it could be clearer or if there is a more appropriate way to enforce such behavior:</p>
<pre><code>// Ensure that only 1 model is ever special.
this.on('change:special', function (changedModel, special) {
if (special) {
this.each(function (model) {
if (model !== changedModel) {
model.set('special', false);
}
});
}
});
</code></pre>
<p>I don't like this because it seems overly verbose and also gives a period of time where two items are special.</p>
|
[] |
[
{
"body": "<p>That seems wrong on a few levels. </p>\n\n<ul>\n<li>Slows down every update call</li>\n<li>This is pretty much 'magic happens here'</li>\n<li>I feel this should be enforced in the UI, is it not too late for this in Backbone?</li>\n</ul>\n\n<p>I would modify the setter to accomplish what you need : <a href=\"https://stackoverflow.com/a/9415926/7602\">https://stackoverflow.com/a/9415926/7602</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:37:04.487",
"Id": "39391",
"ParentId": "39338",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T22:20:37.797",
"Id": "39338",
"Score": "2",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "Backbone.Collection - Ensure that at most one model has property set to true"
}
|
39338
|
<p>I would appreciate it if someone experienced in F# and/or functional programming to look over my code. This is practically the first thing I wrote in the language so I'm sure it's filled with non-idiomatic stuff and unoptimized code.</p>
<p>I'm not interested in implementing a more efficient algorithm. Just implementing this one more efficiently.</p>
<p>If it makes it easier to follow my code the procedure is simple. A "spot" is rectangle on the screen. It has X, Y, Width and Height. It represents a place where you can place a rectangle that's smaller or equal to the spot. </p>
<p>Take a list of rectangles (mutable). Make a list one one possible spot where the first rectangle can fit. It's at (0, 0) with the size (max, max).</p>
<p>Then for every rectangle find the best spot where it can fit and where the maximum value out of his up most Y coordinate and right most X coordinate is minimal. In essence, if we had only that rectangle placed and we wanted to close it in a square that started at (0, 0), find the position where that square would have the lowest area and side's length.</p>
<p>We add two new possible spots. One on the top left corner of the placed rectangle, one at the bottom right. We also go through all other spots we didn't take and cut them if they intersect with our rectangle so when we test new rectangles later we don't get an intersection (due to the rectangle not fitting because we cut the width and height of the spot).</p>
<p>Currently, I have the same thing written in C# and it's a bit faster when I benchmark it. I'm not sure if this can be improved. Buiding it in release mode actually made it slower though that might just be me messing something up.</p>
<p>Anyways, here's the monstrosity:</p>
<pre><code>type IRectangle =
abstract member X : double with get, set
abstract member Y : double with get, set
abstract member Width : double
abstract member Height : double
abstract member Id : int
type internal Spot(x: double, y: double, width: double, height: double) =
member this.x = x
member this.y = y
member this.width = width
member this.height = height
member this.cut = fun (rect: IRectangle) ->
let intervalIntersect : double -> double -> double -> double -> bool =
fun start1 end1 start2 end2 -> min (end1 - start2) (end2 - start1) > 0.0;
let horizontalIntersect = intervalIntersect x (x + width) rect.X (rect.X + rect.Width)
let verticalIntersect = intervalIntersect y (y + height) rect.Y (rect.Y + rect.Height)
if (horizontalIntersect && rect.Y >= y) then
Spot(x, y, width, min (rect.Y - y) height)
elif (verticalIntersect && rect.X >= x) then
Spot(x, y, min (rect.X - x) width, height)
else this
module Packer =
let private initialSpots: Spot list = [Spot(0.0, 0.0, System.Double.MaxValue, System.Double.MaxValue)]
let private bestSpot (rect: IRectangle) (spots: Spot list) =
spots
|> Seq.filter (fun spot -> spot.width >= rect.Width && spot.height >= rect.Height)
|> Seq.sortBy (fun spot -> max (spot.x + rect.Width) (spot.y + rect.Height))
|> Seq.head
let private putRectangle (rect: IRectangle) (spots: Spot list): Spot list =
let best = bestSpot rect spots
rect.X <- best.x
rect.Y <- best.y
let right = Spot(best.x + rect.Width, best.y, best.width - rect.Width, best.height)
let top = Spot(best.x, best.y + rect.Height, best.width, best.height - rect.Height)
spots
|> Seq.filter (fun spot -> spot <> best)
|> Seq.map (fun spot -> spot.cut rect)
|> Seq.append [right; top]
|> List.ofSeq
let rec private putRectangles (rectangles: IRectangle list) (spots: Spot list) =
match rectangles, spots with
| [], _ -> ()
| rect::rest, _ -> putRectangles rest (putRectangle rect spots)
let packRectangles (rectangles: IRectangle list) =
let ordered = Seq.sortBy (fun (rect: IRectangle) -> -(rect.Width * rect.Height)) rectangles
putRectangles (List.ofSeq ordered) initialSpots
List.ofSeq ordered
</code></pre>
<p>The interface is there because I need to interop with C#.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:38:04.287",
"Id": "65923",
"Score": "1",
"body": "Others have answered this well enough, but one other little improvement: `Seq.sortBy` + `Seq.head` can be replaced with `Seq.maxBy`."
}
] |
[
{
"body": "<p>A few comments:</p>\n\n<pre><code> let intervalIntersect : double -> double -> double -> double -> bool = \n fun start1 end1 start2 end2 -> min (end1 - start2) (end2 - start1) > 0.0;\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>let intervalIntersect = fun start1 end1 start2 end2 -> min (end1 - start2) (end2 - start1) > 0.0;\n</code></pre>\n\n<p>There are many places where you have unnecersary types</p>\n\n<p>Also, it is more idiomatic in F# to use <code>float</code> rather than <code>double</code> (although they are exactly the same)</p>\n\n<p>Some of the helper functions could also be moved outside where they are called - i.e. </p>\n\n<pre><code>member this.cut = fun (rect: IRectangle) ->\n let intervalIntersect : double -> double -> double -> double -> bool = \n fun start1 end1 start2 end2 -> min (end1 - start2) (end2 - start1) > 0.0;\n\n let horizontalIntersect = intervalIntersect x (x + width) rect.X (rect.X + rect.Width)\n let verticalIntersect = intervalIntersect y (y + height) rect.Y (rect.Y + rect.Height)\n\n if (horizontalIntersect && rect.Y >= y) then\n Spot(x, y, width, min (rect.Y - y) height)\n elif (verticalIntersect && rect.X >= x) then\n Spot(x, y, min (rect.X - x) width, height)\n else this\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>let intervalIntersect = fun start1 end1 start2 end2 -> min (end1 - start2) (end2 - start1) > 0.0;\nlet horizontalIntersect = intervalIntersect x (x + width) rect.X (rect.X + rect.Width)\nlet verticalIntersect = intervalIntersect y (y + height) rect.Y (rect.Y + rect.Height)\nmember this.cut = fun (rect: IRectangle) ->\n if (horizontalIntersect && rect.Y >= y) then\n Spot(x, y, width, min (rect.Y - y) height)\n elif (verticalIntersect && rect.X >= x) then\n Spot(x, y, min (rect.X - x) width, height)\n else this\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T16:23:44.197",
"Id": "65936",
"Score": "0",
"body": "Why is moving the functions outside better here? Because they sound like they could be used elsewhere too?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T01:51:54.607",
"Id": "39350",
"ParentId": "39347",
"Score": "3"
}
},
{
"body": "<p>Your code is nice, there is no immediate horribleness, so my post will be nitpicking.</p>\n\n<p>In terms of personal style, I would remove all private/internal modifiers, this is really for interop with the legacy language C# :)</p>\n\n<p>I think your interval function is experiencing some repetition in terms of the expression used, but I don't have time to work out a reduction at the moment.</p>\n\n<p>Second, lets remove this type annotation, it is unnecessary as F# can trivially work out the type based on the expression.</p>\n\n<pre><code>let initialSpots: Spot list = [Spot(0.0, 0.0, System.Double.MaxValue, System.Double.MaxValue)]\n</code></pre>\n\n<p>to</p>\n\n<pre><code>let initialSpots = [Spot(0.0, 0.0, System.Double.MaxValue, System.Double.MaxValue)]\n</code></pre>\n\n<p>Next, the optimiser may get rid of it, but you may be able to refactor this:</p>\n\n<pre><code>spots\n|> Seq.filter (fun spot -> spot <> best)\n|> Seq.map (fun spot -> spot.cut rect)\n|> Seq.append [right; top]\n|> List.ofSeq\n</code></pre>\n\n<p>To this (you may need to tweak ordering of yield):</p>\n\n<p>Edit (thanks, I messed something up, I blame the weather)</p>\n\n<pre><code>[ yield! [right;top]\n for spot in spots do \n if spot <> best then \n yield spot.cut rect ]\n</code></pre>\n\n<p>Edit2: Removed complexity statement.\nThis will mean that you don't loop over the 'spots' data at worst twice.</p>\n\n<p>Also the following:</p>\n\n<pre><code>let packRectangles (rectangles: IRectangle list) = \n let ordered = Seq.sortBy (fun (rect: IRectangle) -> -(rect.Width * rect.Height)) rectangles\n putRectangles (List.ofSeq ordered) initialSpots\n List.ofSeq ordered\n</code></pre>\n\n<p>Could be changed to:</p>\n\n<pre><code>let packRectangles (rectangles: IRectangle list) = \n let ordered = List.sortBy (fun (rect: IRectangle) -> -(rect.Width * rect.Height)) rectangles\n putRectangles ordered initialSpots\n ordered\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T16:17:57.107",
"Id": "65934",
"Score": "0",
"body": "1. How does your `if` get rid of O(n) `filter`? The `if` is also O(n). 2. I think that `right` and `top` should be appended only once at the end of the whole result, not after each spot, like your code does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T17:38:09.407",
"Id": "65952",
"Score": "0",
"body": "He probably meant that there are two O(n) operations there (the filter and the map). Also, I'm not sure how scoping works in F# but I'm guessing that indent before right and top are a mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:16:46.733",
"Id": "66002",
"Score": "0",
"body": "@svick i removed the o(n), I wrongly assumed that since both map and filter iterate over the sequence twice, that they will at worst case cause 1 unnecessary iteration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:45:03.213",
"Id": "66006",
"Score": "0",
"body": "out of curiosity i ghetto bench-marked it: http://codepad.org/KcqQN5tl"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:20:21.060",
"Id": "66019",
"Score": "0",
"body": "@DavidK Ah, indentation in query expressions can have such a big impact? I didn't know that."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:40:40.053",
"Id": "39375",
"ParentId": "39347",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39375",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T00:52:41.160",
"Id": "39347",
"Score": "4",
"Tags": [
"algorithm",
"f#"
],
"Title": "F# rectangle packing algorithm"
}
|
39347
|
<p><a href="http://projecteuler.net/problem=12" rel="nofollow">Project Euler Problem 12</a> asks (paraphrased):</p>
<blockquote>
<p>Considering triangular numbers <em>T</em><sub><em>n</em></sub> = 1 + 2 + 3 + … + <em>n</em>, what is the first <em>T</em><sub><em>n</em></sub> with over 500 divisors? (For example, <em>T</em><sub>7</sub> = 28 has six divisors: 1, 2, 4, 7, 14, 28.)</p>
</blockquote>
<p>I have written the following solution. The code is calculates the correct answer, but the run time is appalling (6m9s on a 2.4GHz i7!!!)...</p>
<p>I know Python is definitely not the fastest of languages, but I'm clearly missing a trick here.</p>
<p>Could anyone highlight any optimizations that could be made to bring the execution time down to something sensible?</p>
<pre><code>from math import sqrt, floor
class findDivisors:
def isPrime(self, num):
for i in range(2, int(floor(sqrt(num)) + 1)):
if not num % i:
return False
return True
def numDivisors(self, num):
factors = {}
numFactors = 2
currNum = num
currFactor = 2
while not self.isPrime(currNum):
if not currNum % currFactor:
if currFactor not in factors:
factors[currFactor] = 1
else:
factors[currFactor] += 1
currNum = currNum / currFactor
else:
currFactor += 1
if currNum not in factors:
factors[currNum] = 1
else:
factors[currNum] += 1
total = 1
for key in factors:
total *= factors[key] + 1
return total
def firstWithNDivisors(self, noDivisors):
triGen = genTriangular()
candidate = triGen.next()
while self.numDivisors(candidate) < noDivisors:
candidate = triGen.next()
return candidate
def genTriangular():
next = 1
current = 0
while True:
current = next + current
next += 1
yield current
if __name__ == '__main__':
fd = findDivisors()
print fd.firstWithNDivisors(5)
</code></pre>
<p>Addendum: I have since made to revisions of the code The first is the alteration made as suggested by nabla; check for currentNum being > 1 instead of prime. This gives an execution time of 2.9s</p>
<p>I have since made a further improvement by precomputing the first 10k primes for quick lookup. This improves runtime to 1.6s and is shown below. Does anyone have any suggestions for further optimisations to try and break below the 1s mark?</p>
<pre><code>from math import sqrt, floor
from time import time
class findDivisors2:
def __init__(self):
self.primes = self.initPrimes(10000)
def initPrimes(self, num):
candidate = 3
primes = [2]
while len(primes) < num:
if self.isPrime(candidate):
primes.append(candidate)
candidate += 1
return primes
def isPrime(self, num):
for i in range(2, int(floor(sqrt(num)) + 1)):
if not num % i:
return False
return True
def primeGen(self):
index = 0
while index < len(self.primes):
yield self.primes[index]
index += 1
def factorize(self, num):
factors = {}
curr = num
pg = self.primeGen()
i = pg.next()
while curr > 1:
if not curr % i:
self.addfactor(factors, i)
curr = curr / i
else:
i = pg.next()
return factors
def addfactor(self, factor, n):
if n not in factor:
factor[n] = 1
else:
factor[n] += 1
def firstWithNDivisors(self, num):
gt = genTriangular()
candidate = gt.next()
noDivisors = -1
while noDivisors < num:
candidate = gt.next()
factors = self.factorize(candidate)
total = 1
for key in factors:
total *= factors[key] + 1
noDivisors = total
return candidate
def genTriangular():
next = 1
current = 0
while True:
current = next + current
next += 1
yield current
if __name__ == '__main__':
fd2 = findDivisors2()
start = time()
res2 = fd2.firstWithNDivisors(500)
fin = time()
t2 = fin - start
print "Took", t2, "s", res
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:40:49.647",
"Id": "66023",
"Score": "0",
"body": "Is prime is checking *every* number from 2 to sqrt(n). Half of those are even numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:28:23.760",
"Id": "66130",
"Score": "0",
"body": "Can't believe I missed that, good spot (y)"
}
] |
[
{
"body": "<p>Here is one possible improvement:</p>\n\n<p>Don't check whether <code>currNum</code> is prime, instead simply search factors until <code>currNum</code> becomes <code>1</code>. Checking for prime takes <code>O(sqrt(n))</code> time, but the rest of the loop checking for factors takes approximately <code>O(1)</code> per loop iteration, so you can save those <code>O(sqrt(n))</code> here:</p>\n\n<pre><code> while currNum > 1:\n if not currNum % currFactor:\n if currFactor not in factors:\n factors[currFactor] = 1\n else:\n factors[currFactor] += 1\n currNum = currNum / currFactor\n else:\n currFactor += 1\n\n total = 1\n for key in factors:\n total *= factors[key] + 1\n</code></pre>\n\n<p>Result and timing for <code>firstWithNDivisors(300)</code> with the original code:</p>\n\n<pre><code> 2162160 2.21085190773\n</code></pre>\n\n<p>and without checking for prime:</p>\n\n<pre><code> 2162160 0.0829100608826\n</code></pre>\n\n<p>In fact with this improvement alone the <code>firstWithNDivisors(501)</code> only takes 2.3 sec on my machine.</p>\n\n<p>There are very likely much more efficient algorithms to do this. One can probably make use of the fact that the <code>n</code>-th triangle number is <code>n*(n+1)/2</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T17:26:04.487",
"Id": "65950",
"Score": "0",
"body": "Thanks for a good suggestion, this made a world of difference! I managed to enhance the run-time further by precomputing primes. This has run time on my machine down to 1.6s. Any further suggestions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:07:25.143",
"Id": "65974",
"Score": "1",
"body": "Precomputing primes would have been my next suggestion, also you can calculate the number of divisors for `n` and `n+1` separately because they are coprime, then you can save one the result of `n+1` as `n` for the next run, effectively reducing runtime by a factor of 2. But there are surly much better algorithmic approaches that I haven't looked into."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T02:37:04.123",
"Id": "39351",
"ParentId": "39348",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39351",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T01:15:29.247",
"Id": "39348",
"Score": "5",
"Tags": [
"python",
"optimization",
"project-euler",
"mathematics",
"lookup"
],
"Title": "Project Euler Problem 12 - Highly Divisible Triangular Number - Python Solution Optimization"
}
|
39348
|
<p>I am writing a program that is based on the Travelling Salesman Problem. There are four cities in which the user determines its x and y coordinates. The salesman always starts at city1 and ends up at city1, so there are 6 possible routes. However, each route has an equivalent route, i.e <code>route1</code> has the same distance as <code>route6</code>. I have accounted for this. I've also tried to account for if (route1 or route6) and (route2 or route4) have the same distance. The program tells you that.</p>
<pre><code>import java.util.Scanner;
import java.lang.Math;
public class CityDistancesProgram
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//x and y coordinates of each city
int x1, y1, x2, y2, x3, y3, x4, y4;
//Variable for the distances of each route
double route1, route2, route3, route4, route5, route6;
//Since the distance from cityA to cityB is the same as the distance from cityB to cityA,
//these are all the possible combinations of distances between each city
double city1city2, city2city3, city3city4, city4city1, city2city4, city3city1;
double city2city1, city3city2, city4city3, city1city4, city4city2, city1city3;
double shortestRoute;
System.out.println("Enter the value of each city's x-coordinate and y-coordinate");
System.out.println(" ");
//First city
System.out.println("City 1's x-coordinate:");
x1 = keyboard.nextInt();
System.out.println("City 1's y-coordinate:");
y1 = keyboard.nextInt();
//Second city
System.out.println("City 2's x-coordinate:");
x2 = keyboard.nextInt();
System.out.println("City 2's y-coordinate:");
y2 = keyboard.nextInt();
//Third city
System.out.println("City 3's x-coordinate:");
x3 = keyboard.nextInt();
System.out.println("City 3's y-coordinate:");
y3 = keyboard.nextInt();
//Fourth city
System.out.println("City 4's x-coordinate:");
x4 = keyboard.nextInt();
System.out.println("City 4's y-coordinate:");
y4 = keyboard.nextInt();
System.out.println(" ");
System.out.println("City 1's coordinates are: (" + x1 + ", " + y1 +")");
System.out.println("City 2's coordinates are: (" + x2 + ", " + y2 +")");
System.out.println("City 3's coordinates are: (" + x3 + ", " + y3 +")");
System.out.println("City 4's coordinates are: (" + x4 + ", " + y4 +")");
//Computing all possible combinations of distance between each city
city1city2 = Math.sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)); //distance from city1 to city2
city3city1 = Math.sqrt((x1 - x3)*(x1 - x3) + (y1 - y3)*(y1 - y3)); //distance from city1 to city3
city4city1 = Math.sqrt((x1 - x4)*(x1 - x4) + (y1 - y4)*(y1 - y4)); //distance from city4 to city1
city2city3 = Math.sqrt((x2 - x3)*(x2 - x3) + (y2 - y3)*(y2 - y3)); //distance from city2 to city3
city3city4 = Math.sqrt((x3 - x4)*(x3 - x4) + (y3 - y4)*(y3 - y4)); //distance from city3 to city4
city2city4 = Math.sqrt((x2 - x4)*(x2 - x4) + (y2 - y4)*(y2 - y4)); //distance from city2 to city4
city2city1 = city1city2; //distance from city2 to city1
city3city2 = city2city3; //distance from city3 to city2
city4city3 = city3city4; //distance from city4 to city3
city1city4 = city4city1; //distance from city1 to city4
city4city2 = city2city4; //distance from city4 to city2
city1city3 = city3city1; //distance from city1 to city3
//Computing the distance of each possible route
route1 = city1city2 + city2city3 + city3city4 + city4city1;
route2 = city1city2 + city2city4 + city4city3 + city3city1;
route3 = city1city3 + city3city2 + city2city4 + city4city1;
route4 = city1city3 + city3city4 + city4city2 + city2city1;
route5 = city1city4 + city4city2 + city2city3 + city3city1;
route6 = city1city4 + city4city3 + city3city2 + city2city1;
System.out.println(" ");
System.out.println("The first route has a total distance of " + route1 + " km");
System.out.println("The second route has a total distance of " + route2 + " km");
System.out.println("The third route has a total distance of " + route3 + " km");
System.out.println("The fourth route has a total distance of " + route4 + " km");
System.out.println("The fifth route has a total distance of " + route5 + " km");
System.out.println("The sixth route has a total distance of " + route6 + " km");
shortestRoute = Math.min(Math.min(route1, Math.min(route2,route3)), Math.min(route4,Math.min(route5,route6)));
System.out.println(" ");
boolean r1 = shortestRoute == route1 || shortestRoute == route6;
boolean r2 = shortestRoute == route2 || shortestRoute == route4;
boolean r3 = shortestRoute == route3 || shortestRoute == route5;
if(r1 && r2 && r3)
{
System.out.println("Every route has the same distance, there is no best route");
}
else if(r1 && r2)
{
System.out.println("route1, route2, route4 and route6 are the best routes");
}
else if(r1 && r3)
{
System.out.println("route1, route3, route5 and route6 are the best routes");
}
else if(r2 && r3)
{
System.out.println("route2, route3, route4 and route5 are the best routes");
}
else if(r1)
{
System.out.println("route1 and route6 are the best routes");
}
else if(r2)
{
System.out.println("route2 and route4 are the best routes");
}
else
{
System.out.println("route3 and route5 are the best routes");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T04:19:23.587",
"Id": "65869",
"Score": "2",
"body": "Welcome back! Please add a bit more context, so that people that didn't see your [previous migrated post](http://stackoverflow.com/questions/21152873/travelling-salesman-based-question) don't have to infer everything the code does from the code itself :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T04:40:36.957",
"Id": "65870",
"Score": "1",
"body": "I took the liberty of adding your original text (actually @Jamal's edit), feel free to rollback or edit as you like. I'm sure reviews are coming!"
}
] |
[
{
"body": "<p>The biggest high-level comment I have is that you need to learn about <a href=\"http://en.wikipedia.org/wiki/Modular_programming\">modularity</a>; that is, how to divide your code into separate components that act independently, so that you can reuse those components instead of copy-pasting and editing code. The basic unit of modularity in most programming languages is the function.</p>\n\n<hr>\n\n<p>Let's start with a simple example. You repeat the following lines 4 times with slight modifications:</p>\n\n<pre><code>System.out.println(\"City 1's x-coordinate:\");\nx1 = keyboard.nextInt();\nSystem.out.println(\"City 1's y-coordinate:\"); \ny1 = keyboard.nextInt();\n</code></pre>\n\n<p>Instead, let's define a little data structure and function (quick note: all the code in this answer is untested -- there may be typos in here):</p>\n\n<pre><code>public class Coordinate {\n public final int x;\n public final int y;\n public Coordinate(int x, int y) {\n this.x = x;\n this.y = y;\n }\n}\n\nCoordinate readCityCoordinate(int i) {\n System.out.format(\"City %d's x-coordinate%n\");\n int x = keyboard.nextInt();\n System.out.format(\"City %d's y-coordinate%n\");\n int y = keyboard.nextInt();\n return new Coordinate(x, y);\n}\n</code></pre>\n\n<p>And in the calling function, you'll write</p>\n\n<pre><code>List<Coordinate> cityCoordinates = new ArrayList<>();\nfor (int i = 1; i <= 4; i++) {\n cityCoordinates.add(readCityCoordinate(i));\n}\n</code></pre>\n\n<hr>\n\n<p>OK, the next thing to think about it the overall reusability of this code. Today you want to be able to enter 4 cities' coordinates, compute the shortest route, and then print out the result. Tomorrow, you may be writing some mapping software, and you'll have a bunch of cities in your dataset, and each user may ask you the length of a different route. You may want to do other things with the data, too. The idea is to separate the things that pertain to this general class of problem from the things that are specific to this particular problem (find the shortest route among four cities). Let's make a flexible class design that you may be able to extend later.</p>\n\n<pre><code>import java.util.Iterable;\nimport java.util.List;\n\npublic class RoutePlanner {\n private List<Coordinate> landmarkCoordinates;\n\n public class Coordinate {\n public final int x;\n public final int y;\n public Coordinate(int x, int y) {\n this.x = x;\n this.y = y;\n }\n }\n\n public RoutePlanner(List<Coordinate> landmarkCoordinates) {\n this.landmarkCoordinates = landmarkCoordinates;\n }\n\n // \n public double computeRouteDistance(Iterable<Integer> route) {\n // We'll fill this in later\n }\n // We may add more class members later, too.\n}\n</code></pre>\n\n<hr>\n\n<p>OK, we've figure out the general shape of our main abstraction. That will drive the design of the <code>main</code> function. We'll want to do the following things:</p>\n\n<ol>\n<li>Read in the coordinates of our four cities.</li>\n<li>Build a <code>RoutePlanner</code> out of these landmarks.</li>\n<li>Compute the length of each route.</li>\n<li>Figure out which routes are shortest.</li>\n<li>Print out the shortest routes.</li>\n</ol>\n\n<p>That tells us how <code>main</code> should be written! Each set should correspond to a function call or perhaps 2-3 lines in your main function.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Scanner;\n\nclass CityDistancesProgram {\n private static Scanner keyboard = new Scanner(System.in);\n\n public static void main(String[] args) {\n List<RoutePlanner.Coordinate> cityCoordinates = new ArrayList<>();\n for (int i = 1; i <= 4; i++) {\n cityCoordinates.add(readCityCoordinate(i));\n }\n\n RoutePlanner planner = new RoutePlanner(cityCoordinates);\n\n List<List<Integer>> routes = enumerateRoutes();\n\n List<Double> distances = new ArrayList<>();\n for (List<Integer> route : routes) {\n distances.add(planner.computeRouteDistance(route));\n }\n\n List<Integer> shortestRoutes = findIndicesOfMinima(distances);\n\n printShortestRoutes(shortestRoutes, distances);\n }\n\n /** Prompt the user for the coordinates of city number i */\n private RoutePlanner.Coordinate readCityCoordinate(int i) {\n // Defined above\n }\n\n /** Returns a list of all circuits through the four cities. */\n private List<List<Integer>> enumerateRoutes() {\n }\n\n /**\n * Returns of a list of the indices of all of the elements\n * that are equal to the minimum value in the input list.\n */\n private List<Integer> findIndicesOfMinima(List<Double> distances) {\n }\n\n /** Prints out which routes were shortest. */\n private void printShortestRoutes(List<Integer> shortestRoutes\n List<Double> distances) {\n }\n}\n</code></pre>\n\n<p>Now a reader can look at your <code>main</code>, and in a few seconds figure out how the program works. Now let's talk about the helper functions!</p>\n\n<hr>\n\n<p>The first is <code>enumerateRoutes</code>, which is pretty straightforward. The idea is that we want to produce values that we can feed to <code>RoutePlanner</code>'s <code>computeRouteDistance</code> method.</p>\n\n<pre><code> private List<List<Integer>> enumerateRoutes() {\n // Note: you can generalize this to list all permutations of\n // 0, 1, ..., n that begin with 0, but let's hold on to this\n // for now -- permutation code is much more complicated than\n // this, so it doesn't seem worth it when we know we have\n // only four cities.\n List<List<Integer>> routes = new ArrayList<>();\n routes.add(Arrays.asList(0, 1, 2, 3, 0));\n routes.add(Arrays.asList(0, 1, 3, 2, 0));\n routes.add(Arrays.asList(0, 2, 1, 3, 0));\n routes.add(Arrays.asList(0, 2, 3, 1, 0));\n routes.add(Arrays.asList(0, 3, 1, 2, 0));\n routes.add(Arrays.asList(0, 3, 2, 1, 0));\n return routes;\n }\n</code></pre>\n\n<p>You'll note that these routes use a 0-based index system, not a 1-based index system. That's only sensible, as that's what Java uses!</p>\n\n<hr>\n\n<p>Now <code>findIndicesOfMinima</code>. I favor an approach that keeps a running tab on which values are currently minimum, rather than computing the minimum and then going back through the list to find which values actually match it.</p>\n\n<pre><code> private List<Integer> findIndicesOfMinima(List<Double> distances) {\n List<Integer> indices = new ArrayList<>();\n indices.add(0);\n double minimum = distances.get(0);\n\n for (int i = 1; i < distances.size(); i++) {\n double d = distances.get(i);\n if (d < minimum) {\n indices.clear();\n indices.add(i);\n minimum = d;\n } else if (d == minimum) {\n indices.add(i);\n }\n }\n return indices;\n }\n</code></pre>\n\n<hr>\n\n<p>OK, we're up to <code>printShortestRoutes</code>. Instead of coming up with an <code>if-else</code> block with a slightly different bit of code in each stanza, let's try to generalize.</p>\n\n<pre><code> private void printShortestRoutes(List<Integer> shortestRoutes,\n List<Double> distances) {\n assert(shortestRoutes.size() >= 2);\n if (shortestRoutes.size() == 2) {\n System.out.format(\n \"route%d and route%d are the best routes (distance %f)%n\",\n shortestRoutes.get(0), shortestRoutes.get(1),\n distances.get(shortestRoutes.get(0));\n } else {\n for (int i = 0; i < shortestRoutes.size() - 1; i++) {\n System.out.format(\"route%d, \", shortestRoutes.get(i));\n }\n System.out.format(\n \"and route%d are the best routes (distance %f)%n\",\n shortestRoutes.get(shortestRoutes.size() - 1),\n distances.get(shortestRoutes.get(0)));\n }\n }\n</code></pre>\n\n<p>This could be made a bit cleaner, but it gives the general idea.</p>\n\n<hr>\n\n<p>The last thing to write is <code>RoutePlanner.computeRouteDistance</code>.</p>\n\n<pre><code>public double computeRouteDistance(Iterable<Integer> route) {\n double distance = 0.0;\n Iterator<Integer> it = route.iterator();\n if (!it.hasNext()) return 0;\n int prev = it.next();\n while (it.hasNext()) {\n int next = it.next();\n distance += computeDistance(prev, next);\n prev = next;\n }\n return distance;\n}\n\nprivate double computeDistance(int i, int j) {\n Coordinate ci = landmarkCoordinates.get(i);\n Coordinate cj = landmarkCoordinates.get(j);\n return Math.sqrt((ci.x - cj.x) * (ci.x - cj.x)\n + (ci.y - cj.y) * (ci.y - cj.y));\n}\n</code></pre>\n\n<hr>\n\n<p>That's it for a first pass! Some general rules of thumb to keep in mind:</p>\n\n<ul>\n<li>Try not to repeat yourself in code (this is known in some circles as <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">the DRY principle</a>).</li>\n<li>If you can break a function down into logical steps, each step should probably be a function call.</li>\n<li>If you can't think of a good name that describes what a function is doing, it should probably be two or more functions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:24:30.740",
"Id": "65889",
"Score": "4",
"body": "Excellent! I would add another rule of thumb for programmers: there should be 0, 1, or 2 of something. If you have 3 or more, it's probably time to generalize. Therefore, if you have 3 variables for cities, that's a sign that they should be replace with something like an array or list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T05:49:22.550",
"Id": "39354",
"ParentId": "39353",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "39354",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T04:10:50.403",
"Id": "39353",
"Score": "12",
"Tags": [
"java",
"traveling-salesman"
],
"Title": "Travelling salesman with four cities"
}
|
39353
|
<p>I want to see if I can make any improvements to the rendering methods that are currently written. I've noticed when profiling this project that the CPU was allocating a fair percentage of the time towards rendering and was wondering if there were any improvements that I can make towards it.</p>
<p>Note: Below is my somewhat simple rendering method. I am rendering an ArrayList of tiles, few of these are transparent. This function (<code>y*map.getMapWidth())+x</code>) will return the index in the ArrayList to be rendered.</p>
<p><code>ImageManager</code> is a class that stores cropped images from a spritesheet as a <code>BufferedImage</code>.</p>
<pre><code>import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
public class Game extends Canvas implements Runnable{
private void renderTiles(Graphics g) {
// the overlay variable determines if I need to render anything off screen
// (True if player is moving)
int overlay = 0;
if (moving) {
overlay = 1;
}
// the four variables below determine the starting/finishing x/y variables
// to begin rendering
int startX = -((xOffset/(Tile.TILESIZE*SCALE))+overlay);
int finishX = -(((xOffset-(WIDTH*SCALE))/(Tile.TILESIZE*SCALE))-overlay);
int startY = -((yOffset/(Tile.TILESIZE*SCALE))+overlay);
int finishY = -(((yOffset-(HEIGHT*SCALE))/(Tile.TILESIZE*SCALE))-overlay);
// to avoid crashes, the variables can't render what isn't there in the list
if (startX < 0) {
startX = 0;
} if (finishX > map.getMapWidth()) {
finishX = map.getMapWidth();
} if (startY < 0) {
startY = 0;
} if (finishY > map.getMapHeight()) {
finishY = map.getMapHeight();
}
// where the tiles are render. tiles are stored in an ArrayList so that
// switching between maps is easier
for (int y = startY; y < finishY; y++) {
for (int x = startX; x < finishX; x++) {
map.tile.get((y*map.getMapWidth())+x).render(g);
}
}
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(2);
return;
}
Graphics g = bs.getDrawGraphics();
// start rendering
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
renderTiles(g);
player.render(g);
g.dispose();
bs.show();
}
}
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public abstract class Tile {
public static final int TILESIZE = 16;
protected BufferedImage bi;
protected ImageManager im;
protected int x, y, oX, oY;
protected Game game;
public Tile(int x, int y, ImageManager im, Game game, BufferedImage bi){
this.oX = x;
this.oY = y;
this.im = im;
this.game = game;
this.bi = bi;
}
public abstract void tick();
public abstract void render(Graphics g);
}
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class WalkableTerrainTile extends Tile{
public WalkableTerrainTile(int x, int y, ImageManager im, Game game, BufferedImage bi) {
super(x, y, im, game, bi);
}
public void tick() {
this.game = game;
x = oX + game.xOffset;
y = oY + game.yOffset;
}
public void render(Graphics g) {
g.drawImage(bi, x, y, Tile.TILESIZE * Game.SCALE, Tile.TILESIZE * Game.SCALE, null);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not sure if these would be optimized out by the compiler but</p>\n\n<pre><code>Tile.TILESIZE * SCALE\nTile.TILESIZE * Game.SCALE\n</code></pre>\n\n<p>are done more than once, why not just keep them as variables and...</p>\n\n<pre><code>for (int y = startY; y < finishY; y++) {\n for (int x = startX; x < finishX; x++) {\n map.tile.get((y*map.getMapWidth())+x).render(g);\n</code></pre>\n\n<p>...why do a multiplication for every <code>y</code>? you could just have a variable and increment it</p>\n\n<pre><code>int yLoc = startY * map.getWidth();\nfor (int y = startY; y < finishY; y++) {\n for (int x = startX; x < finishX; x++) {\n map.tile.get(yLoc+x).render(g);\n }\n yLoc += map.getMapWidth();\n}\n</code></pre>\n\n<p>then you only need to do one multiplication and one addition for each <code>y</code> step instead of a multiplication for every <code>y</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:51:38.940",
"Id": "65884",
"Score": "0",
"body": "Shouldn't the declaration of `yloc` be inside the first loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:54:30.340",
"Id": "65885",
"Score": "0",
"body": "I think you mean the increment of `yLoc`. If the declaration was inside, then it would always be equal to the map width. I've fixed it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:17:22.993",
"Id": "65887",
"Score": "1",
"body": "Ahh that is some good advice there. Thank you. I want to try and flesh out as much performance as I can."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:25:05.817",
"Id": "39369",
"ParentId": "39355",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39369",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T06:33:24.990",
"Id": "39355",
"Score": "3",
"Tags": [
"java",
"performance",
"image"
],
"Title": "Improving rendering performance of 2D Tile Game"
}
|
39355
|
<p>I am working on a CoderByte problem in JavaScript. I have solved the problem below. Although I am trying to figure out if there is an easier way to do it? I am guessing RegEx will come up, although I don't have experience with that yet. </p>
<p>From CoderByte: </p>
<blockquote>
<p>Using the JavaScript language, have the function SimpleSymbols(str)
take the str parameter being passed and determine if it is an
acceptable sequence by either returning the string true or false. The
str parameter will be composed of + and = symbols with several letters
between them (ie. ++d+===+c++==a) and for the string to be true each
letter must be surrounded by a + symbol. So the string to the left
would be false. The string will not be empty and will have at least
one letter.</p>
</blockquote>
<p>My implementation:</p>
<pre><code>var str = "++d+===+c++=";
var simpleSymbols = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] != '+' && str[i] != '=' && !(str[i] >= 'a' && str[i - 1] == '+' && str[i + 1] == '+')) {
return false;
}
}
return true;
}
simpleSymbols(str);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:32:15.447",
"Id": "65989",
"Score": "0",
"body": "regex can be very messy for anything more complicated than this. better to learn how to do things without it first, then try to do the regex version, because regex is very useful if used correctly and in the right places"
}
] |
[
{
"body": "<p>First off, my solution was way more convoluted ;)</p>\n\n<p>Other than that, 2 minor points</p>\n\n<ul>\n<li>It is good practice to have a shortcut to [].length in general</li>\n<li>Since 'a' is larger than '+' and '=' ( in the ASCII table ) you can drop a part of the logic</li>\n</ul>\n\n<p>So you could try something like</p>\n\n<pre><code>var simpleSymbols = function (s) {\n for (var i = 0, length = s.length; i < length; i++) {\n if ( s[i] >= 'a' && s[i - 1] != '+' && s[i + 1] != '+' ) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T08:11:48.170",
"Id": "66496",
"Score": "0",
"body": "why are you doing `length = s.length;`? looks like extra code to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T19:29:31.177",
"Id": "66555",
"Score": "0",
"body": "@Malachi, it caches the lookup of .length, it is a common performance approach. Not sure about your other comment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:49:42.037",
"Id": "39385",
"ParentId": "39356",
"Score": "5"
}
},
{
"body": "<p>How about this logic?</p>\n\n<ol>\n<li>if the first character or last character is a letter it's false</li>\n<li>then go through the array and look for the letters\n<ul>\n<li>skip it if is a <code>=</code> or a <code>+</code></li>\n<li>if it isn't a <code>=</code> or a <code>+</code> then check that the character before and after is a <code>+</code></li>\n</ul></li>\n</ol>\n\n<p>So something like this:</p>\n\n<pre><code>var simpleSymbols = function (s) {\n if (s[0] != \"+\" && s[0] != \"=\") {\n return false;\n } else if (s[s.length - 1] != \"+\" && s[s.Length - 1] != \"=\") {\n return false;\n } else {\n for (var i = 1; i<s.Length - 1; i++) {\n if (s[i] != \"+\" && s[i] != \"=\") {\n if (s[i-1] != \"+\" || s[i+1] != \"+\") {\n return False;\n }\n }\n }\n }\n return true;\n}\n</code></pre>\n\n<p>This code is cleaner than what you have. </p>\n\n<p>With this block of code:</p>\n\n<ol>\n<li>it's more readable</li>\n<li>it exits if the first or last character is a letter, immediately preventing unnecessary iterations in a for loop.</li>\n<li>it's easier to read</li>\n<li>it's easier to follow (in my opinion)</li>\n</ol>\n\n<hr>\n\n<h2>Bottom Line</h2>\n\n<p>Your code is not efficient. All of the <code>if</code> statements fire every iteration until the end of the string is met or a return is met.</p>\n\n<ol>\n<li>if the last character is a letter, will return false and not loop through the whole string.</li>\n<li>will not perform a \"before and after check\" unless the character is a letter</li>\n</ol>\n\n<p>It may not make a difference in smaller strings, but if you have a huge string to parse, it will make a difference.</p>\n\n<hr>\n\n<p>I have been told the the CoderBytes challenge will include numbers that don't need to be surrounded by <code>+</code>'s, and I wanted to steal a little of @Konijn's answer as well.</p>\n\n<p>All of my above points still stand for this code block as well.</p>\n\n<pre><code>var simpleSymbols = function (s) {\n if (s[0] >= 'a' || s[s.length -1] >= 'a') {\n return false;\n } else {\n for (var i = 1; i<s.length - 1; i++) {\n if (s[i] >= 'a') {\n if (s[i-1] != \"+\" || s[i+1] != \"+\") {\n return false;\n }\n }\n }\n }\n return true;\n}\n</code></pre>\n\n<p><strong>NOTE</strong></p>\n\n<p>This code is the most efficient way to perform this task. </p>\n\n<ol>\n<li><p>It exits if the first or last character is a letter because you can't have a <code>+</code> before the first character or a <code>+</code> after the last character, thus failing the filter.</p></li>\n<li><p>It only checks the before and after characters if the character is a letter. This prevents unnecessary if statements from being performed</p></li>\n<li><p>All the other answers so far will check every character and the before and after character until it <code>return</code>s. This could be an issue if the string is say 500,000 characters long, you would see a definite decrease in performance.</p></li>\n<li><p>This code will not loop through the whole string if there is a letter in the last character position, which would make it a lot more efficient in those cases.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:29:10.867",
"Id": "39413",
"ParentId": "39356",
"Score": "7"
}
},
{
"body": "<blockquote>\n <p>I am guessing RegEx will come up</p>\n</blockquote>\n\n<p>If I understand the problem correctly, here's a possible regex solution:</p>\n\n<pre><code>function simpleSymbols(str) {\n var letters = str.match(/[a-z]/gi);\n var matches = str.match(/\\+[a-z]\\+/gi);\n if (! str.length || ! matches) {\n return false;\n }\n return letters.length == matches.length;\n}\n</code></pre>\n\n<p>The function above takes a string, extracts its letters, and its matches with the pattern <code>+letter+</code>. If the string is empty or there are no matches, return false; otherwise check there if there are as many letters as matches, if so, then the string validates.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:20:58.700",
"Id": "39424",
"ParentId": "39356",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T06:39:19.850",
"Id": "39356",
"Score": "7",
"Tags": [
"javascript",
"strings",
"parsing",
"programming-challenge"
],
"Title": "Coderbyte SimpleSymbols challenge in Javascript"
}
|
39356
|
<p>I have this class which is used as part of a game. It needs to generate Random Even values, which is done by generating random numbers until the result is even.</p>
<p>Is there a better way to do this?</p>
<p>Also, I currently have the methods implemented as private instance methods, but should I declare <code>generateRandomNumber()</code> and <code>evenNumber(number)</code> as static methods? Will it have any benefits?</p>
<pre><code>public class Game {
//...
public void opponentSaysEvenNumber() {
int number = generateRandomEvenNumber();
System.out.println("Opponent: " + number);
}
private int generateRandomEvenNumber() {
Random random = new Random();
int number = random.nextInt();
while (!evenNumber(number)) {
number = random.nextInt();
}
return number;
}
private boolean evenNumber(int number) {
return (number % 2) == 0;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T02:35:36.563",
"Id": "66038",
"Score": "17",
"body": "Just wondering, why not just multiply whatever number you receive from the RNG by 2?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T06:20:31.373",
"Id": "66051",
"Score": "5",
"body": "Add 1 to the odd ones that is generated?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T08:59:11.590",
"Id": "66066",
"Score": "1",
"body": "@WetFeet why \"multiply by 2\" when you can more simply \"add 1\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:11:33.263",
"Id": "66068",
"Score": "4",
"body": "@lohoris Because the 'add 1' operation requires you to test beforehand whether you have an odd or even number, so it's one test and one add operation, or just one test and a null; 'multiply by 2' *always* yields an even number, so it's always just a single operation that can be reduced to a 'bitwise left shift by 1' at assembly level. I don't think it's possible to *get* much faster than that..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:13:28.207",
"Id": "66069",
"Score": "4",
"body": "... Except maybe using a bit mask to zero the least significant bit, come to think of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:14:02.610",
"Id": "66070",
"Score": "2",
"body": "I also would recommend a left shift operation, and for completeness sake, would like to point out bitwise AND'ing with NOT(1) would work as well (in one operation)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:14:35.643",
"Id": "66072",
"Score": "0",
"body": "@Shadur, beat me to it as I was writing the comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:15:30.950",
"Id": "66073",
"Score": "0",
"body": "@BolucPapuccuoglu Great minds think alike. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:17:26.527",
"Id": "66081",
"Score": "2",
"body": "I suspect \"multiply by 2\" is the option that distorts the distribution of the random number the least, if that's important (although I can't really back that feeling up, but Math.SE would know)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:52:28.647",
"Id": "114871",
"Score": "0",
"body": "Yes, I would declare them as `private static`; [this StackOverflow answer](http://stackoverflow.com/questions/538870/java-static-methods-best-practices) provides some good information."
}
] |
[
{
"body": "<p>Declaring such methods <code>static</code> can increase the readability of your code. For the reader it will be obvious that the method does not depend on the internal state of an instance of the class. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:19:03.173",
"Id": "65888",
"Score": "2",
"body": "What's more calling `static` method is a little bit faster (no implicit passing of `this` to the method)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:51:26.933",
"Id": "66027",
"Score": "1",
"body": "@Adam I'm pretty sure that would get compiled out of the resulting bytecode."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:53:10.670",
"Id": "39363",
"ParentId": "39359",
"Score": "22"
}
},
{
"body": "<p>Yes. I would <del>go one step further and</del> declare your functions as <code>private static</code> <del><code>final</code></del>, if possible. The combination of those <del>three</del> keywords means that the code would be unaffected by any instance variable, any superclass, or any subclass, and is also not callable by any code external to the class. Therefore, the compiler has enough of a hint that it could decide to inline the entire function.</p>\n\n<p>I would also rename <code>evenNumber(int number)</code> to <code>isEven(int number)</code>. There is a convention in Java that functions named <code>isSomething()</code> return a <code>boolean</code> and have no side effects. Your function meets those criteria.</p>\n\n<p>To generate a random even number, you could just take <code>random.nextInt() & -2</code> to mask off the least significant digit. That would be more efficient than looping, testing, and discarding. In that case, the whole question about helper functions would be irrelevant.</p>\n\n<p>It's bad practice to create a new instance of <code>Random</code> every time you want to generate one random number, though. The pseudorandom number generator actually carries some state, even if you don't think of it that way. You should therefore use a <code>private static</code> variable to store the <code>Random</code> object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:43:27.917",
"Id": "65905",
"Score": "4",
"body": "`final` does nothing to a **private** static method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:41:23.300",
"Id": "65911",
"Score": "0",
"body": "@omiel will the JIT still inline it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:59:31.300",
"Id": "65914",
"Score": "4",
"body": "Static methods are not part of the inheritance, so there is no way for another class to over-ride them anyway. That's why final is meaningless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:37:59.270",
"Id": "65922",
"Score": "1",
"body": "Would there be a reasonable argument that adding final improves future readability?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T17:33:25.513",
"Id": "65951",
"Score": "0",
"body": "@200_success Welcome to the discussion about naming predicate-methods. codereview.stackexchange.com/questions/39399/naming-of-predicate-methods"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:07:55.020",
"Id": "66008",
"Score": "2",
"body": "before using a private static Random variable, consider the following excerpt from the javadoc: Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:51:24.110",
"Id": "66154",
"Score": "0",
"body": "Once upon a time, it was a Bad Thing to create your random every time for two reasons: 1) it seeded off of system time, so multiple calls in the same time slice of system time granularity would result in the same 'random' result, and 2) garbage collection wasn't optimized for short lived objects. Now, random creature seeds off of time and an independent state manipulator to combat that flaw, and most modern JVMs can spin objects up and down without the massive overhead of old. I still don't recommend creating your Random inside your method, but it's near as Bad of a Thing as it once was."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:06:39.053",
"Id": "39372",
"ParentId": "39359",
"Score": "43"
}
},
{
"body": "<p>If you don't use any of the attributes of the class, then it means that you should probably put this method somewhere else. Maybe in another class, a <code>RandomEvenNumberGenerator</code> for example.</p>\n\n<p>I've always considered static a bad practice. It opens the path to so many problems, semantic issues and \"I know where you live\" syndrome, which in turns make testing harder, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:44:28.177",
"Id": "65891",
"Score": "1",
"body": "Could you elaborate what the \"I know where you live\" syndrome is in the context of unit testing? Google did not help me out on this one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:59:21.727",
"Id": "65893",
"Score": "0",
"body": "Unit testing is testing each component, each class in total separation from the others, to avoid any incontrollable side effects. Typically, you will have a hard time testing a component that's using a singleton, because you can't easily substitute the singleton with something you control. The component \"knows where the singleton lives\" and addresses directly to it. The better way would be to provide an instance of the singleton to the object that needs it. In the code given, it wouldn't really hurt, but having `static` methods encourages this coding style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:49:30.377",
"Id": "65926",
"Score": "5",
"body": "No, if this method is used in that class by its methods and nowhere else, it should certainly be static private. This makes a lot more sense than having a static class full of disparate helper functions, or a different class for each helper function. Static non-private methods in non-static classes are a different story. Your argument against singletons isn't really applicable here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:42:04.230",
"Id": "66005",
"Score": "0",
"body": "\"private static\" used this way for helper functions is pointless and misleading. It can be considered bad practice. The word \"static\" adds uneccesary syntactic noise, and it might be taken as a warning that there is some kind of singleton mechanism hidden somewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:11:21.600",
"Id": "66067",
"Score": "0",
"body": "@jwg, I never advertised the `Utility` class. Of course not. Having this method as static in this class forces to recreate a new `Random` instance each time we call the method, or else we need to share it as static property (danger!). I agree with Ichthyo in that it adds unnecessary code noise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:22:59.287",
"Id": "66074",
"Score": "0",
"body": "The argument about unit testing is completely bogus: 1. Private methods do not need to be tested. 2. `Random` is a standard component which does not need to be 'replaced with something you control'. As I said, if the method were not private it would be different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:24:07.677",
"Id": "66075",
"Score": "0",
"body": "You need to understand that, when talking about unit tests, I was referring to `static` in general, not in this specific case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:24:46.183",
"Id": "66076",
"Score": "0",
"body": "Well then, your argument is that the word `static` (6 chars) makes the code unnecessarily verbose?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:39:01.343",
"Id": "39374",
"ParentId": "39359",
"Score": "9"
}
},
{
"body": "<p>Declaring a static and unique random number generator method is a good choice if you want to centralize the generation of those numbers. However, don't forget to also mark the method as <code>synchronized</code> if you're planning to run your code in a multithreaded environment.</p>\n\n<p>You should also declare the <code>Random</code> instance as <code>private final static</code>. </p>\n\n<p>Finally, as the <code>evenNumber</code> method consists of a single test, you could move that test to your <code>generateRandomEvenNumber</code> method and have your class composed by only two methods.</p>\n\n<p>Another possibility if you want to centralize the generation of those random numbers is to create a <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">Singleton</a> random numbers generator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:03:47.097",
"Id": "66007",
"Score": "0",
"body": "I agree with you insofar the `generateRandomEvenNumber` should be moved out of that class, since it isn't related to the core concern of this Game class. But I disagree on the inlining of `evenNumber`. You loose the self-documenting through the name, and you force the user to figure out what the code does. And it would violate the \"single level of abstraction\" principle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:08:39.260",
"Id": "66421",
"Score": "0",
"body": "Nice point about the \"single level of abstraction\" principle, Jamal, thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:21:25.433",
"Id": "39389",
"ParentId": "39359",
"Score": "1"
}
},
{
"body": "<p>Your technique is inefficient. To generate even numbers, just do any of the following:</p>\n\n<ul>\n<li><p>Mask off the least significant bit (<code>-2</code> is <code>0xFFFFFFFE</code>, or a bitmask with all ones except for the last bit)</p>\n\n<pre><code>random.nextInt() & -2;\n</code></pre></li>\n<li><p>Shift left by one bit using the bit-shift operator</p>\n\n<pre><code>random.nextInt() << 1;\n</code></pre></li>\n<li><p>Shift left by one bit using multiplication</p>\n\n<pre><code>random.nextInt() * 2;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:35:41.653",
"Id": "66021",
"Score": "0",
"body": "Well spotted. At least the op should write if(!evenNumber(number))number++, so he wouldn't generate other random number"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T03:48:36.237",
"Id": "66042",
"Score": "2",
"body": "Using a bit mask is not acceptable because it modifies the number distribution. Ex: random outputs 2,3 become 2,2. Shifting left or multiplying are the only acceptable way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T04:48:20.893",
"Id": "66046",
"Score": "4",
"body": "@Carl No it doesn't (at least not for positive integers - for negative or positive integers there might be a slight bias around zero, but this doesn't apply here). All even numbers still occur with the same probability (they all can be output by the PRNG outputting themselves, or the number immediately following them)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:48:48.800",
"Id": "66077",
"Score": "0",
"body": "There's a little flaw, when you multiply or shift left, you need to keep into account that you are working on integers, not unsigned integers, and a overflow will result in change of sign."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T03:45:08.210",
"Id": "66619",
"Score": "0",
"body": "@DarioOO Overflow doesn't matter. All three techniques result in 31 random bits followed by a 0 bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T18:19:17.230",
"Id": "66686",
"Score": "1",
"body": "from that point of view you are right, but most random numbers assume positive result only. Take for example user wants numbers from 0 to 6, it will do % by 7. but since also negative integer is returned, due to % sign rules, the real result is numbers in range [-6,6]."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:46:13.110",
"Id": "39419",
"ParentId": "39359",
"Score": "15"
}
},
{
"body": "<p>You do not want to mask to make your elements even. There are an odd number of positive and an odd number of negative values. This can throw you for a loop (no pun intended) by causing them to be slightly biased.</p>\n\n<p>Instead, you want to provide a min and max and find an even number in that range. You want to do this by shifting (actually division and multiplication, but because we're dealing with a power of 2 we can do it with bit shifts) and not with rounding (which is what masking is essentially).</p>\n\n<p>As a general rule of thumb, you don't want to throw away random bits when you don't have to.</p>\n\n<pre><code>private static final Random rand = new Random(); \n\npublic static int randomEvenNumber(int min, int max) {\n if(min % 2 != 0) throw new IllegalArgumentException(\"Minimum value must be even\");\n if(max % 2 != 0) throw new IllegalArgumentException(\"Maximum value must be even\");\n int range = max - min;\n int rangeHalf = range >> 1; // divided by 2\n int randomValue = rand.nextInt(rangeHalf);\n randomValue = randomValue << 1; // multiplied by 2 to make it even\n return min + randomValue;\n}\n\npublic static final int randomEvenNumber(int max) {\n return randomEvenNumber(0,max);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T03:17:00.173",
"Id": "66041",
"Score": "0",
"body": "To be fair, if you care that much about bias, you probably don't want to use `java.util.Random` to begin with. This would also be more readable and just as efficient if you did `* 2` and `/ 2` instead of shifting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T07:02:10.390",
"Id": "66055",
"Score": "2",
"body": "It depends what you consider to be \"fair\". Masking off the LSB (or shifting off the MSB) does pick numbers from the set of all representable even `int`s with uniform probability. However, since there is one more representable negative even number than there are representable positive even numbers, you correctly note that the distribution is not exactly centered at 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:21:27.787",
"Id": "66091",
"Score": "0",
"body": "Instead of throwing exceptions on min and max, why not use the rounded values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:45:52.440",
"Id": "66152",
"Score": "0",
"body": "@Henek Min and max parameters typically use the following contract: Min is the lowest acceptable value, and max is the first value greater than the highest acceptable value. If min was not even, it would not be an acceptable value which breaks the contract. The case for max is similar. One could argue that those conditions do not belong there. For example, randomEvenNumber(9,19) might have solution set {10,12,14,16,18} - the logic would be slightly more intricate (determine if min is odd and adjust accordingly) but would not involve rounding."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T01:00:13.280",
"Id": "39432",
"ParentId": "39359",
"Score": "2"
}
},
{
"body": "<p>Why not just double the first random number generated and return it? You will still have random numbers, their distribution is not corrupted and its faster.</p>\n\n<pre><code>public class Game {\n //...\n\n public void opponentSaysEvenNumber() {\n int number = generateRandomEvenNumber();\n System.out.println(\"Opponent: \" + number);\n }\n\n private int generateRandomEvenNumber() {\n Random random = new Random();\n int number = random.nextInt();\n return number * 2;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T03:46:49.837",
"Id": "39441",
"ParentId": "39359",
"Score": "9"
}
},
{
"body": "<p>Perhaps a higher-level approach may get you to a better solution.</p>\n\n<p>The random generator methods (generateRandomEvenNumber() and evenNumber()) are mathematical in nature and really not specific to the game. They have no dependencies on the game class (e.g. they don't use fields) and they have no side effects.</p>\n\n<p>My approach would be to do something like this. Create a RandomService class with those methods and inject an instance of the service into the game. Using Spring or some other DI (dependency injection) framework, the service can be created as a singleton. The methods on RandomService can be public because they have no dependencies or side effects and they are easily testable, separately from the game.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:26:38.087",
"Id": "39485",
"ParentId": "39359",
"Score": "2"
}
},
{
"body": "<p>Consider using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadLocalRandom.html\" rel=\"nofollow noreferrer\">ThreadLocalRandom</a></p>\n\n<pre><code>private int generateRandomEvenNumber() {\n return ThreadLocalRandom.current().nextInt() & -2;\n}\n</code></pre>\n\n<p>ThreadLocalRandom was added in Java 7 and <a href=\"http://java-performance.info/java-util-random-java-util-concurrent-threadlocalrandom-multithreaded-environments/\" rel=\"nofollow noreferrer\">solves</a> a few performances issues with the Random object, especially in multi-threaded environments. Even if you're not in a multi-treaded environment, I think it is a good idea to use it every time. Furthermore the Api is nicer than the old Random one (you don't have to create the object, just use the static method).</p>\n\n<p>Using <code>& -2</code> (or any other method proposed by <a href=\"https://codereview.stackexchange.com/a/39419/49356\">@wizzi poo</a>) will ensure the generated number is always even by setting the last bit of the generated number to 0. This is better than doing a while as there is always the chance Random could never generate an even number (highly unlikely).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T10:11:32.013",
"Id": "57375",
"ParentId": "39359",
"Score": "5"
}
},
{
"body": "<p>Another option is to add or subtract 1 in case of odd random number.</p>\n\n<pre><code>...\nnumber = random.nextInt();\nif (number % 2 == 1) {\n number++;\n number %= MAX_NUMBER; // assuming upper limit is required\n}\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-19T22:59:55.730",
"Id": "70353",
"ParentId": "39359",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "39372",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:34:23.097",
"Id": "39359",
"Score": "34",
"Tags": [
"java",
"random",
"static"
],
"Title": "Generating Even Random Numbers"
}
|
39359
|
<p>I want to implement a Type system for different representations of an angle value. Motivation to implement this as a type system comes from <a href="https://stackoverflow.com/questions/2945471/extending-the-net-type-system-so-the-compiler-enforces-semantic-meaning-of-prim/2945498">this question</a>.</p>
<p>Angle can be represented using the following types: </p>
<ul>
<li><code>Degrees</code> (45.5) </li>
<li><code>Degrees</code> <code>Minutes</code> <code>Seconds</code>, <code>DMS</code> (45*30'00") </li>
<li><code>Radians</code> (0.7941) </li>
</ul>
<p>It should support conversions between types (like <code>Convert.ToInt32(someDouble)</code>), and from system types (to/from double).</p>
<ul>
<li>What properties should this type system have?</li>
<li>Should <code>Degrees</code> types be equal (implemented internally) if we convert from <code>Degrees</code> to <code>Radians</code> and back to <code>Degrees</code>? Or it should be compared as doubles with Epsilon value outside?</li>
<li>In what cases should explicit and implicit conversion operators be used, keeping in mind value precision loss on conversion?</li>
</ul>
<p>Here is the work in progress:</p>
<pre><code> // in current implementation this test will fail
[Test]
public void DegreesToRadiansToDegreesEquivalence()
{
Degree initialDegree = 0;
for (int i = 0; initialDegree < 360; initialDegree += 1, i++)
{
Radian convertedToRadian = (Radian) initialDegree;
Degree resultDegree = (Degree) convertedToRadian;
Assert.AreEqual(initialDegree, resultDegree, Double.Epsilon, String.Format("{0} {1}", i, (double)convertedToRadian));
}
}
public struct Degree
{
private readonly double _value;
// Construct Degree from Double
public Degree(Double value)
{
_value = value;
}
// Converts Degree to Double
private Double ToDouble()
{
return _value;
}
// Implicitly Degree -> Double
public static implicit operator Degree(Double value)
{
return new Degree(value);
}
// Implicitly Degree -> Double
public static implicit operator Double(Degree d)
{
return d.ToDouble();
}
// Explicitly Degree -> Radian
public static explicit operator Degree(Radian r)
{
return ConvertAngle.ToDegree(r);
}
// Explicitly Degree -> Radian
public static explicit operator Radian(Degree d)
{
return ConvertAngle.ToRadian(d);
}
}
// todo better to preserve sign in all fields because otherwise it would be impossible to represent 0°00'-20"
// store sign separate ? easy to implement operators - +
public struct DMS : IEquatable<DMS>
{
public readonly double Degrees;
public readonly double Minutes;
public readonly double Seconds;
public DMS(double degree, double minute, double second)
{
Degrees = Math.Floor(degree);
Minutes = Math.Abs(Math.Floor(minute));
Seconds = Math.Abs(second);
}
public bool Equals(DMS other)
{
return (Math.Abs(other.Degrees - this.Degrees) < double.Epsilon) &&
(Math.Abs(other.Minutes - this.Minutes) < double.Epsilon) &&
(Math.Abs(other.Seconds - this.Seconds) < double.Epsilon);
}
}
public struct Radian
{
private readonly double _value;
// Construct Degree from Double
public Radian(Double value)
{
_value = value;
}
// Converts Degree to Double
private Double ToDouble()
{
return _value;
}
// Implicitly Double -> Radian
public static implicit operator Radian(Double value)
{
return new Radian(value);
}
// Implicitly Radian -> Double
public static implicit operator Double(Radian d)
{
return d.ToDouble();
}
}
public enum AngleFormat
{
Degrees,
DegreesMinutes,
DegreesMinutesSeconds,
Radians
}
public static class ConvertAngle
{
public static Degree ToDegree(Radian radians)
{
return radians * 180.0 / Math.PI;
}
public static Degree ToDegree(DMS dms)
{
// todo seems sign problem here
return dms.Degrees + dms.Minutes / 60 + dms.Seconds / 3600;
}
public static Radian ToRadian(Degree degrees)
{
return degrees * Math.PI / 180.0;
}
public static Radian ToRadian(DMS dms)
{
return ToRadian((Degree)(dms.Degrees + dms.Minutes / 60 + dms.Seconds / 3600));
}
public static DMS ToDMS(Radian radian)
{
return ToDMS(ToDegree(radian));
}
public static DMS ToDMS(Degree degree)
{
double degrees = Math.Floor(degree);
double rem = (degree - degrees) * 60.0;
double minutes = Math.Floor(rem);
double seconds = (rem - minutes) * 60.0;
return new DMS(degrees, minutes, seconds);
}
public static string ToString(Radian radian, AngleFormat format, int precision)
{
if (format == AngleFormat.Radians)
{
string formStr = "{0:F" + precision + "}";
return String.Format(formStr, radian);
}
else if (format == AngleFormat.Degrees ||
format == AngleFormat.DegreesMinutes ||
format == AngleFormat.DegreesMinutesSeconds)
{
return ToString((Degree)radian, format, precision);
}
throw new NotImplementedException();
return "";
}
public static string ToString(Degree degree, AngleFormat format, int precision)
{
DMS dms = ToDMS(degree);
switch (format)
{
// todo use precision
case AngleFormat.Degrees:
case AngleFormat.DegreesMinutes:
case AngleFormat.DegreesMinutesSeconds:
return ToString(ToDMS(degree), format, precision);
case AngleFormat.Radians:
return ToString((Radian)degree, format, precision);
}
throw new NotImplementedException();
return "";
}
public static string ToString(DMS dms, AngleFormat format, int precision)
{
switch (format)
{
// todo here do we need to combine min and sec ??? or we need diffrent format option
case AngleFormat.Degrees:
return String.Format("{0:D}°", dms.Degrees);
case AngleFormat.DegreesMinutes:
return String.Format("{0:D}°{1:D}'", dms.Degrees, dms.Minutes);
case AngleFormat.DegreesMinutesSeconds:
string secondsPrecisionFormat = "F" + Math.Abs(precision).ToString("D");
//string d = dms.Degrees.ToString("");
//CultureInfo currentCulture = CultureInfo.CurrentCulture;
string stringFormat = "{0:F0}° {1:F0}' {2:" + secondsPrecisionFormat + "}\"";
return String.Format(stringFormat, dms.Degrees, dms.Minutes, dms.Seconds);
case AngleFormat.Radians:
// todo convert to radians ??
break;
}
throw new ArgumentOutOfRangeException("format");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:35:59.907",
"Id": "65878",
"Score": "1",
"body": "Are you asking _us_ what _your_ system should be able to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:51:43.027",
"Id": "65879",
"Score": "0",
"body": "given nature properties, conversion rules of angle representations. What constraints, properties should type system have ? What is wrong right now in implementation?"
}
] |
[
{
"body": "<p>I don't think you should treat the units as disjoint entities between which you convert. You have started your post by saying </p>\n\n<blockquote>\n <p>Angle can be represented using following types</p>\n</blockquote>\n\n<p>But actually what you meant is \"units\".</p>\n\n<p>So the entity you are trying to measure is an angle. And code using it should, for most parts, not care what unit it represents - just that it represents a specific angle. Expressing it as a value in a specific unit is only really necessary for calculations in algorithms which require the angle to be of a specific unit, serialization, display, etc.</p>\n\n<p>Therefore I suggest a different design: You have an <code>Angle</code> type which represents a specific angle. Choose whichever unit you like best as internal representation of it. The type then exposes methods to create an <code>Angle</code> from various value in specific units and convert them to such. Something along these lines:</p>\n\n<pre><code>struct Angle\n{\n private double _Degrees; // I chose degrees as internal representation for an angle but as other have pointed out Radians might be better\n\n private Angle(double degrees)\n {\n _Degrees = degrees;\n }\n\n public static Angle FromDegrees(double degrees)\n {\n return new Angle(Normalize(degrees)); // Ensure angles are in [0-360[\n }\n\n public static Angle FromRadians(double radians)\n {\n return new Angle(RadiansToDegrees(radians));\n }\n\n public static Angle FromDegreesMinutesSeconds(DegreesMinutesSeconds dms)\n {\n return new Angle(DegreesMinutesSecondsToDegrees(dms));\n }\n\n public double AsDegrees()\n {\n return _Degrees;\n }\n\n public double AsRadians()\n {\n return DegreesToRadians(_Degrees);\n }\n\n public DegreesMinutesSeconds AsDegreesMinutesSeconds()\n {\n return DegreesToDegreesMinutesSeconds(_Degrees);\n }\n} \n</code></pre>\n\n<p>Consider overloading <code>==</code>, <code>!=</code>. You could probably also overload <code><</code>, <code><=</code>, <code>>=</code> and <code>></code>. Although you might have to consider questions like: Is 359 degrees greater or smaller than 5 degrees? </p>\n\n<p>Override <code>Equals</code> and <code>GetHashCode</code> is you overload <code>==</code> (check <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/7h9bszxx%28v=vs.100%29.aspx\" rel=\"nofollow\">Microsoft guidelines</a>).</p>\n\n<p>Overloading <code>+</code> and <code>-</code> (<code>Angle + Angle</code>, <strike><code>Angle + scalar</code></strike>, <code>Angle - Angle</code>, <strike><code>Angle - scalar</code></strike>) as well as <code>*</code> and <code>/</code> (<code>Angle * scalar</code>, <code>Angle / scalar</code>) makes for nicer calculations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T11:53:31.067",
"Id": "65897",
"Score": "2",
"body": "How would angle + scalar behave? I think that doesn't make much sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T08:18:55.447",
"Id": "66882",
"Score": "0",
"body": "As @svick noted above, Angle + scalar does not make sense unless it is perfectly obvious that the \"default\" unit of an Angle is for example degrees.\nAlso, you chose degrees as the internal representation unit for the Angle - I would chose to use radians instead (the preferred SI unit for generic angles).\nOtherwise, this is pretty much the approach that I would have used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T08:57:28.513",
"Id": "66884",
"Score": "0",
"body": "@svick good point"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T12:40:13.947",
"Id": "134134",
"Score": "1",
"body": "This is quite similar to `TimeSpan` in .NET. You can ask \"how many minutes\" or \"how many seconds\" it has, or conversely create a new one with `TimeSpan.FromSeconds()`, or `TimeSpan.FromMinutes()`. Internally, it is represented by `Ticks`, whatever that might be :o)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-18T17:14:12.117",
"Id": "217883",
"Score": "0",
"body": "`Angle / Angle` which returns a scalar is also another operator you may wish to implement."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:52:48.063",
"Id": "39366",
"ParentId": "39360",
"Score": "13"
}
},
{
"body": "<p>Your implementation will be really hard to maintain as you keep adding different operations. Also the fact that you have multiple classes to represent single entity is kind of weird.</p>\n\n<p>For example, look at <code>DateTime</code> implementation. It represents time in various formats via exposed properties and formattable <code>ToString</code> and <code>Parse</code> methods. But when it comes to manipulating <code>DateTime</code> values - it essentially comes down to manipulating <code>Ticks</code> (which is just one of the possible representations--the easiest one to deal with). I think you should do the same. Create a single <code>Angle</code> class, expose different representation via properties (<code>Radians</code>, <code>Minutes</code>, <code>Seconds</code>, <code>Degrees</code>, etc.), but when it comes to calculations - deal with radians representation only.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:56:14.847",
"Id": "39367",
"ParentId": "39360",
"Score": "7"
}
},
{
"body": "<p>I'd consider a simpler, single class:</p>\n\n<pre><code>class Angle\n{\n // The 'native' type, passed to System.Math methods\n public double Radians { get; set;}\n // Factory methods\n public static Angle FromRadians(double d) { ... }\n public static Angle FromDegrees(double d) { ... }\n public static Angle FromDegrees(int degrees, int minutes, double seconds) { ... }\n // Display methods\n public string ToRadians(int precision) { ... }\n public string ToDegrees(int precision) { ... }\n}\n</code></pre>\n\n<p>I imagine that ToDegrees returns a string which you can display on a UI.</p>\n\n<p>The difference between my answer and @ChrisWue's are:</p>\n\n<ul>\n<li>I use radians as the internal/native unit, because they're what are expected by System.Math methods</li>\n<li>I avoid returning degrees as a number (I return them as a string), to discourage users from performing calculations using degree -> radian -> degree conversions.</li>\n</ul>\n\n<p>For your DMS type, perhaps \"degrees\" and \"minutes\" should be integer (not double) types.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:34:33.670",
"Id": "65890",
"Score": "8",
"body": "That awkward moment when one realizes that you and @ChrisWue are two different persons (conspiracy theories aside) :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:03:19.157",
"Id": "39371",
"ParentId": "39360",
"Score": "8"
}
},
{
"body": "<p>I see only one reason for having different representation. And that's precision errors. Degrees and radians probably will have different offsets when represented in <code>double</code>. But since almost any trigonometry operations will use radians there is not so much gain.\nYou can just keep degrees and other reps temporary and/or in storage to show same value user entered, but eventually they will be converted to radians.</p>\n\n<p>Consider radians to be angle value without any annotation and assumed by default for double that comes as angle. And just create value types that will be converted whenever you need work.</p>\n\n<pre><code>struct Degree {\n public double Value;\n public Degree(double value) : Value(value) {}\n public double AsRadians { get { return /* to radians */; } }\n public static Degree Radians(double d) { return /* from radians */; }\n public static implicit operator double(Degree d) { return d.AsRadians; }\n public static implicit operator Degree(double d) { return Radians(d); }\n public static explicit operator Degree(double d) { return Radians(d); }\n /* any operation require conversion to radians */\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T21:37:24.697",
"Id": "39564",
"ParentId": "39360",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:36:00.757",
"Id": "39360",
"Score": "12",
"Tags": [
"c#",
"mathematics",
"converting",
"type-safety"
],
"Title": "Type system for different representations of angle value"
}
|
39360
|
<p>Please review the code for code cleanup, smart optimizations and best practices. Also verify my complexity: \$O(n^2)\$, where \$n\$ is the number of nodes.</p>
<pre><code>/**
* This class traverses the tree and returns in-order representation.
* This class does not recursion and does not use stack.
* This code is threadsafe.
*/
public final class TraversalWithoutRecursionWithoutStack<T> {
private TreeNode<T> root;
/**
* Constructs a binary tree in order of elements in an array.
* The input list is treated as BFS representation of the list.
* Note that it is the clients reponsibility to not modify input list in objects lifetime.
*
* http://codereview.stackexchange.com/questions/31334/least-common-ancestor-for-binary-search-tree/31394?noredirect=1#comment51044_31394
*/
public TraversalWithoutRecursionWithoutStack(List<T> items) {
create(items);
}
/**
* Idea of inner class is supported by linked list and another code found here:
* http://stackoverflow.com/questions/5262308/how-do-implement-a-breadth-first-traversal
*
* @author SERVICE-NOW\ameya.patil
*/
private static class TreeNode<T> {
TreeNode<T> left;
T item;
TreeNode<T> right;
TreeNode(TreeNode<T> left, T item, TreeNode<T> right) {
this.left = left;
this.item = item;
this.right = right;
}
}
private void create (List<T> items) {
root = new TreeNode<T>(null, items.get(0), null);
final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode<T> current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode<T>(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<T>(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
private TreeNode<T> getInorderSuccessor(TreeNode<T> node) {
assert node != null;
TreeNode<T> inorderSuccessorCandidate = node.left;
while (inorderSuccessorCandidate.right != null && inorderSuccessorCandidate.right != node) {
inorderSuccessorCandidate = inorderSuccessorCandidate.right;
}
return inorderSuccessorCandidate;
}
/**
* Returns the list containing items in inorder form.
*
* @returns the list of items in inorder.
*/
public List<T> inorderTraversal () {
final List<T> nodes = new ArrayList<T>();
TreeNode<T> node = root;
while (node != null) {
if (node.left == null) {
nodes.add(node.item);
node = node.right;
continue;
}
final TreeNode<T> inorderSuccessor = getInorderSuccessor(node);
if (inorderSuccessor.right == null) {
inorderSuccessor.right = node;
node = node.left;
} else {
inorderSuccessor.right = null;
nodes.add(node.item);
node = node.right;
}
}
return nodes;
}
public static void main(String[] args) {
/**
* 1
* 2 3
* 4 n n 7
*/
Integer[] arr1 = {1, 2, 3, 4, null, null, 7};
List<Integer> list1 = new ArrayList<Integer>();
for (Integer i : arr1) {
list1.add(i);
}
TraversalWithoutRecursionWithoutStack<Integer> traversalWithoutRecursionWithoutStack1 = new TraversalWithoutRecursionWithoutStack<Integer>(list1);
System.out.print("Expected: 4 2 1 3 7, Actual: ");
for (Integer i : traversalWithoutRecursionWithoutStack1.inorderTraversal()) {
System.out.print(i + " ");
}
System.out.println("\n--------------------------------");
/**
* 1
* 2 3
* 4 n 6 n
*/
Integer[] arr2 = {1, 2, 3, 4, null, 6};
List<Integer> list2 = new ArrayList<Integer>();
for (Integer i : arr2) {
list2.add(i);
}
TraversalWithoutRecursionWithoutStack<Integer> traversalWithoutRecursionWithoutStack2 = new TraversalWithoutRecursionWithoutStack<Integer>(list2);
System.out.print("Expected: 4 2 1 6 3, Actual: ");
for (Integer i : traversalWithoutRecursionWithoutStack2.inorderTraversal()) {
System.out.print(i + " ");
}
System.out.println("\n---------------------------------");
/**
* 1
* / \
* null 2
* / \ / \
* null null null 3
* / \ / \ / \ / \
* null null null null null null null 4
*
*/
Integer[] arr3 = {1, null, 2, null, null, null, 3, null, null, null, null, null, null, null, 4};
List<Integer> list3 = new ArrayList<Integer>();
for (Integer i : arr3) {
list3.add(i);
}
TraversalWithoutRecursionWithoutStack<Integer> traversalWithoutRecursionWithoutStack3 = new TraversalWithoutRecursionWithoutStack<Integer>(list3);
System.out.print("Expected: 1 2 3 4, Actual: ");
for (Integer i : traversalWithoutRecursionWithoutStack3.inorderTraversal()) {
System.out.print(i + " ");
}
System.out.println("\n---------------------------------");
/**
* 4
* / \
* 2 null
* / \ / \
* 1 null null null
*/
Integer[] arr4 = {4, 2, null, 1, null};
List<Integer> list4 = new ArrayList<Integer>();
for (Integer i : arr4) {
list4.add(i);
}
TraversalWithoutRecursionWithoutStack<Integer> traversalWithoutRecursionWithoutStack4 = new TraversalWithoutRecursionWithoutStack<Integer>(list4);
System.out.print("Expected: 1 2 4, Actual: ");
for (Integer i : traversalWithoutRecursionWithoutStack4.inorderTraversal()) {
System.out.print(i + " ");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T11:13:38.557",
"Id": "65894",
"Score": "0",
"body": "there would be no need to unbalance the tree if you have a parent pointer in TreeNode"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T11:48:59.767",
"Id": "65896",
"Score": "0",
"body": "Modifying a node with `inorderSuccessor.right = node;` during `inorderTraversal()`, making the data structure not a tree, feels like such a dirty hack, even if you undo it later."
}
] |
[
{
"body": "<p>I have a few comments on your code and algorithm.</p>\n\n<p>First, I don't understand why you cannot use recursion or a stack. You have not elaborated on this. If it is because this is a learning exercise then perhaps I can understand, but it is a poor example of any normal data-structure manipulation...</p>\n\n<p>If this is a real application then I would have to question the whole thing.... Essentially you are taking a list of Data, and converting it in to a List of data.... there is no apparent manipulation of the data at all (at least from the end-user perspective).</p>\n\n<p>I simply do not see much value in this code.</p>\n\n<p>Still, assuming I am missing something important, what about the actual code? Unfortunately recommending changes while not using a stack or recursion is very challenging.... it's like you have been told to screw two pieces of wood together, but you are not allowed to use a screwdriver.... Ratchet-freak's comment/suggestion to add the parent-node is the right solution... and that fixes a lot, but, without that, there is nothing I feel happy recommending other than some big-picture structural items.... </p>\n\n<p>Your class is being treated as the source-data for a loop:</p>\n\n<pre><code>for (Integer i : traversalWithoutRecursionWithoutStack4.inorderTraversal()) {\n ....\n}\n</code></pre>\n\n<p>This implies that your class should be <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html\" rel=\"nofollow\"><code>java.lang.Iterable</code></a> and it is not. If you used this then you can simply:</p>\n\n<pre><code>for (Integer i : traversalWithoutRecursionWithoutStack4) {\n ....\n}\n</code></pre>\n\n<p>As for the data structure, since the code is a 'decorator' for an input list, you should just add the parent-node pointer and be done with it. It is something you know in your <code>create</code> method so there is no extra work. Alternatively, just use <strong>stack</strong>, or use <strong>recursion</strong>.</p>\n\n<p>As for the complexity of the algorithm, it is only <em>O(n<sup>2</sup>)</em> if your input List is an ArrayList or some other <em>O(1)</em> access list. If the input is a LinkedList itself, then your complexity jumps to <em>O(n<sup>3</sup>)</em>. You should find an <em>O(1)</em> way to step through the List in your <code>create()</code> method, probably using an Iterator instead of indexed <code>get(...)</code> lookups. An Iterator over the input is the safest way to do it, but, if you have no choice then in the <code>create()</code> method you should check to see whether the List implements <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/RandomAccess.html\" rel=\"nofollow\"><code>java.util.RandomAccess</code></a>, and if it does not, then you should copy the input in to an ArrayList, and index-get off the arraylist....</p>\n\n<pre><code>if (! (items instanceof RandomAccess)) {\n items = new ArrayList<>(items);\n}\n</code></pre>\n\n<p>This turns what would be an <em>O(n<sup>3</sup>)</em> back to one which scales with <em>O(n<sup>2</sup>)</em> complexity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T12:12:41.003",
"Id": "39379",
"ParentId": "39364",
"Score": "3"
}
},
{
"body": "<p>A minor bug: You get an <code>IndexOutOfBoundsException</code> for an empty list in <code>TraversalWithoutRecursionWithoutStack.create(List<T> items)</code>. You don't have a comment stating you need to input a list containing at least something. Consider returning <code>IllegalArgumentException</code> and adding a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-17T11:21:53.310",
"Id": "63148",
"ParentId": "39364",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:21:30.860",
"Id": "39364",
"Score": "3",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Inorder traversal of a tree without recursion or stack"
}
|
39364
|
<p>Please review the code quality of this l33t Speak translator. Improvement suggestions are welcome. Here it is - <a href="http://jsbin.com/IHoFuQE/1" rel="nofollow">http://jsbin.com/IHoFuQE/1</a></p>
<pre><code>(function() {
"use strict";
// http://en.wikipedia.org/wiki/Leet
// http://www.catb.org/jargon/html/crackers.html
var alphabets = { // common
"a": "4",
"b": "8",
"e": "3",
"f": "ph",
"g": "6", // or 9
"i": "1", // or |
"o": "0",
"s": "5",
"t": "7" // or +
},
alphabets2 = { // less common
"c": "(", // or k or |< or /<
"d": "<|",
"h": "|-|",
"k": "|<", // or /<
"l": "|", // or 1
"m": "|\\/|",
"n": "|\\|",
"p": "|2",
"u": "|_|",
"v": "/", // or \/
"w": "//", // or \/\/
"x": "><",
"y": "'/"
};
var words = {
"am": "m",
"are": "r",
"at": "@",
"thanks": "thx",
"your": "ur",
"cool": "kewl",
"defeated": "pwned",
"dude": "d00d",
"fear": "ph33r", // or ph34r
"fool": "f00",
"freak": "phreak",
"hacker": "h4x0r",
"lamer": "l4m3r",
"mad": "m4d",
"newbie": "n00b",
"own": "pwn",
"phone": "fone",
"porn": "pr0n", // or n0rp
"rocks": "roxxorz",
"skill": "sk1llz",
"sucks": "sux0r",
"the": "t3h",
"uber": "ub3r", // or |_|83r
"yay": "w00t",
"yo": "j0",
"you": "j00" // or U
};
var elite = document.getElementById("elite"),
leet = document.getElementById("leet"),
randomcase = document.getElementById("randomcase"),
adv = document.getElementById("adv"),
btn = document.getElementById("btn");
function changeLetters(text) { // change letters
text = text || elite.value.toLowerCase();
for (var i = 0; i < text.length; i++) {
var alphabet = adv.checked ? alphabets[text[i]] || alphabets2[text[i]] : alphabets[text[i]];
if (alphabet) {
text = text.replace(text[i], alphabet);
}
}
return text;
}
function changeWords() { // change special words and return text
return changeLetters().replace(
/\w+/g,
function(word) {
return words[word] ? words[word] : word;
}
);
}
function randomizeCase() { // RANdOMiZE CAsE
var text = changeWords();
for (var i = 0; i < text.length; i++) {
if (Math.random() > 0.5) {
text = text.replace(text[i], text[i].toUpperCase());
} // else keep lower case
}
return text;
}
(function() { // l33t the words object
for (var word in words) {
if (words.hasOwnProperty(word)) {
words[changeLetters(word)] = words[word];
delete words[word];
}
}
}());
function tol33t() {
leet.value = randomcase.checked ? randomizeCase() : changeWords();
}
elite.addEventListener("input", tol33t);
btn.addEventListener("click", tol33t);
}());
</code></pre>
|
[] |
[
{
"body": "<p>To start with, I'd like to give you credit for using <code>\"use strict\"</code> and limiting the scope of variables using functions.</p>\n\n<p>Your <code>tol33t()</code> function is weird to me. If the <code>randomcase</code> button is checked, you call <code>randomizeCase()</code> with no arguments. What are you randomizing the case of? It turns out that <code>randomizeCase()</code> calls <code>changeWords()</code>, so it turns out that the two code branches have something in common after all. That wasn't apparent from looking at <code>tol33t()</code>.</p>\n\n<p>There should be clearer separation responsibility between the DOM-interaction and text-translation layers of code. The text translation code should reside in pure functions (whose results depend solely on their parameters) that you could call from the JavaScript console or from a unit testing engine. That separation of concerns could be accomplished with:</p>\n\n<pre><code>function onTranslateButtonClicked() {\n var l33tText = toL33t(elite.value, adv.checked);\n if (randomcase.checked) l33tText = randomizeCase(l33tText);\n leet.value = l33tText;\n}\n</code></pre>\n\n<p>Your \"l33t the words object\" initialization routine lays a trap for anyone trying to read the code. When code in <code>changeWords()</code> refers to the <code>words</code> associative array, one would reasonably think that it's using the definition above (i.e., <code>words = { \"am\": \"m\", … }</code>) instead of the munged version (<code>words = { \"4m\": \"m\" }</code>). Better to make that munging explicit when you define <code>words</code> (and do so by returning a copy rather than mutating the dictionary as you iterate):</p>\n\n<pre><code>var words = l33tKeys({\n \"am\": \"m\",\n …\n});\n\nfunction l33tKeys(dict) {\n var l33tDict = {};\n for (var word in dict) {\n l33tDict[changeWord(word)] = dict[word];\n }\n return l33tDict;\n}\n</code></pre>\n\n<p>I would write <code>changeLetters()</code> as:</p>\n\n<pre><code> // letterSubsts may be alphabet or alphabet2\nfunction changeLetters(text, letterSubsts) {\n return text.toLowerCase().replace(/[a-z]/g, function(letter) {\n return letterSubsts[letter] || letter;\n });\n}\n</code></pre>\n\n<p>… which is actually analogous to your implementation of <code>changeWords()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T12:47:34.947",
"Id": "65899",
"Score": "0",
"body": "Thank you for your answer. But I'm having problem connecting all these. So would you please modify my jsBin."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T07:46:23.247",
"Id": "66061",
"Score": "0",
"body": "finally I've implemented your changes, please see - http://jsbin.com/AREZoCig/2/edit?js,output"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T08:23:19.377",
"Id": "66063",
"Score": "0",
"body": "But the advanced leet wont work if I use your `changeLetters()`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T11:37:43.297",
"Id": "39376",
"ParentId": "39365",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:38:16.327",
"Id": "39365",
"Score": "6",
"Tags": [
"javascript",
"strings"
],
"Title": "l33t Speak translator"
}
|
39365
|
<p>As an exercise, I wanted to rewrite this toy Python code in Haskell:</p>
<pre><code>def f(x):
return abs(42-x)**2
def improve(x):
newX = x + 0.1
return newX, f(newX)
def optimize(f, goal):
x = 0
err = f(x)
while not err < goal:
x, err = improve(x)
return x, err
print(optimize(f, 0.5))
</code></pre>
<p><a href="http://ideone.com/OPYig7" rel="nofollow">Ideone</a></p>
<p>My solution works but is quite ugly:</p>
<pre><code>f :: (Num a) => a -> a
f x = abs(42-x)^2
improve :: (Fractional a) => (a -> b) -> a -> (a, b)
improve f x =
let newX = x+0.1
in (newX, f newX)
step :: (Fractional a, Ord b) => (a -> b) -> b -> a -> (a, b)
step f goal x =
let
newX = x+0.1
err = f newX
in
if err < goal then (newX, err) else step f goal newX
optimize :: (Fractional a, Ord b) => (a -> b) -> b -> (a, b)
optimize f goal = step f goal 0
main :: IO ()
main = print $ optimize f 0.5
</code></pre>
<p><a href="http://ideone.com/lAheSR" rel="nofollow">Ideone</a></p>
<p>I am trying to find a solution without explicit recursion using a fold or something, but did not have an idea yet on how to do it. Can anybody help me out?</p>
|
[] |
[
{
"body": "<p>The guys at #haskell pointed me to <a href=\"http://zvon.org/other/haskell/Outputprelude/until_f.html\" rel=\"nofollow\">until</a>. This makes it satisfactory to me.</p>\n\n<pre><code>f :: Num a => a -> a\nf x = abs(42-x)^2\n\nimprove :: Fractional b => (b -> c) -> (b, a) -> (b, c)\nimprove f (x, _) = (newX, f newX) where newX = x+0.1\n\noptimize:: (Ord a, Fractional b) => (b -> a) -> a -> b -> (b, a)\noptimize f goal x = until isDone (improve f) (0, f x)\n where isDone (_, err) = err < goal\n\nmain :: IO ()\nmain = print $ optimize f 0.5 0\n</code></pre>\n\n<p><a href=\"http://ideone.com/ZlC7x8\" rel=\"nofollow\">http://ideone.com/ZlC7x8</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T11:58:51.793",
"Id": "39378",
"ParentId": "39370",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39378",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:58:22.740",
"Id": "39370",
"Score": "0",
"Tags": [
"haskell",
"recursion"
],
"Title": "Naïve optimization by stepping until the error falls below a threshold"
}
|
39370
|
<p>The following is a solution to <a href="https://projecteuler.net/problem=12" rel="nofollow noreferrer">Project Euler problem number 12</a>: which is to find the first <a href="http://en.wikipedia.org/wiki/Triangular_number" rel="nofollow noreferrer">triangular number</a> with more than 500 divisors.</p>
<p>The code takes far too long to complete (over 10 minutes). Is there any way to optimize the run-time and to make it more elegant?</p>
<pre><code>#include <iostream>
#include <chrono>
#include <ctime>
inline void triangle(int &num, int &interval)
{
num = ((interval * interval) + interval ) / 2;
}
int main()
{
long int input;
int num = 1, interval = 1, divisor = 1, no_divisor = 0;
std::cout << "Enter factor limit for Triangle number: ";
std::cin >> input;
auto start = std::chrono::steady_clock::now();
for (;;)
{
while (divisor <= num)
{
if (0 == num % divisor) //check factor;
{
std::cout << "factor: " << divisor << "\n";
no_divisor++;
if (no_divisor > input) //divisor count over input number, jump to exit;
{
goto exit;
}
}
divisor++;
}
std::cout << "\n";
interval++;
triangle(num, interval);
divisor = 1; //reset divisor back to 1;
no_divisor = 0; //reset divisor count back to 0;
}
exit: std::cout << "the first Triangle number to have over " << input << " divisors : " << num << "\n";
auto end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "\nIt took me " << elapsed.count() << " milliseconds." << "\n";
return 0;
}
</code></pre>
<h2>Optimization I've done:</h2>
<ol>
<li>using <code>std::cout << "\n"</code> instead of <code>std::cout << endl</code> to prevent flushing output buffers. Source: <a href="https://codereview.stackexchange.com/questions/38069/project-euler-12-in-c-highly-divisible-triangular-number/38079#38079">this</a></li>
<li>using <code>inline void triangle(int &num, int &interval)</code> speed up 10% time</li>
<li>using <strong><em>n</em>(n+1)/2</strong> according to <a href="https://codereview.stackexchange.com/a/39351/35036">this</a></li>
</ol>
<h2>Speculation:</h2>
<p>I figured if the question asked for over 500 factors, which for example:
Triangular number 28 has over 5 factors:</p>
<p><img src="https://i.stack.imgur.com/vYXLI.jpg" alt="enter image description here"></p>
<p>So I only need to iterate up to half of the limit. But how can I implement that into my code to only iterate up to half as many factor?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:52:55.193",
"Id": "65892",
"Score": "1",
"body": "you only need to factor `n` and `n+1` (first divide the even one by 2); they are coprime and thus have mutually exclusive factors so `nd(n*(n+1))=nd(n)*nd(n+1)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:41:51.813",
"Id": "66427",
"Score": "0",
"body": "Here is a tip. Project Euler problems are designed so that they can run under a second (usually, there is always an exception). Analysis of the problem can lead to a better algorithm. Some people (who are extremely talented and/or have too much time) can do project Euler with pen and paper."
}
] |
[
{
"body": "<p>Project Euler problems typically don't benefit from micro-optimizations such as inlining functions or flushing standard output. The biggest speed gains often come from <strong>algorithmic improvements</strong>. Here there are two key mathematical facts that can make this computation tractable:</p>\n\n<ol>\n<li>A number with prime factorisation <code>n = Product_i p_i ^ e_i</code> (where <code>p_i</code> are primes and <code>e_i</code> their exponents) has a number of divisors equal to <code>d = Product_i (e_i + 1)</code>.</li>\n<li>A triangle number is equal to <code>n * (n + 1) / 2</code>. These factors have no prime factors in common and only one of them has a factor of two. This means that the number of divisors of a triangle number can be factored in the number of the divisors of <code>n</code> and <code>n+1</code>. </li>\n</ol>\n\n<p>In order to code this algorithm, a few more guidelines to writing better code:</p>\n\n<ol>\n<li>write functions that take an <code>int</code> and return an <code>int</code>. Don't use Pascal like procedures by modifying a reference argument. This makes your code harder to reason about.</li>\n<li>separate computation from I/O: an algorithm should ideally have no side effects, and be silent. If you want to query the result, just print that.</li>\n</ol>\n\n<p>Below some working code:</p>\n\n<pre><code>#include <chrono>\n#include <ctime>\n#include <iostream>\n\nint triangle(int n)\n{\n return ((n + 1) * n) / 2; \n}\n\n// Math fact: a prime decomposition n = Prod_i p_i^e_i yields\n// Prod_i (e_i + 1) different divisors\nint num_divisors(int n)\n{\n auto divisors = 1; // 1 has one divisor\n {\n auto f = 2;\n auto count = 0;\n while (n % f == 0) {\n ++count;\n n /= f; // divide by factor of 2\n }\n divisors *= (count + 1);\n }\n\n // <= n guarantees that a prime has 2 divisors\n for (auto f = 3; f <= n; f += 2) {\n auto count = 0;\n while (n % f == 0) {\n ++count;\n n /= f; // divide by odd factor\n }\n divisors *= (count + 1);\n }\n return divisors;\n}\n\nint unique_divisors(int n)\n{\n if (n % 2 == 0)\n n /= 2;\n return num_divisors(n);\n}\n\n// triangle(n) = (n + 1) * n / 2\n// only one of them has a factor of two, and they have no prime factors in common\n// we can cache one of the divisor counts while iterating over triangle numbers\nint first_triangle_with_more_than_n_divisors(int n)\n{\n auto i = 1;\n for (auto f1 = unique_divisors(i), f2 = unique_divisors(i + 1); f1 * f2 <= n; ++i) {\n f1 = f2; // re-use result from previous iteration\n f2 = unique_divisors(i + 2); // only one new computation\n }\n return i;\n}\n\nint main()\n{\n auto start = std::chrono::steady_clock::now();\n\n auto const n = 500;\n auto res = first_triangle_with_more_than_n_divisors(n);\n\n std::cout << \"the first Triangle number to have over \" << n << \" divisors : \" << triangle(res) << \"\\n\";\n\n auto stop = std::chrono::steady_clock::now();\n auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);\n\n std::cout << \"\\nIt took me \" << elapsed.count() << \" milliseconds.\" << \"\\n\";\n}\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/f817aebc15aa5e7e\" rel=\"nofollow\"><strong>Live Example</strong></a> that runs in less than 0.2 seconds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T04:11:32.373",
"Id": "66043",
"Score": "0",
"body": "is there any reason you use `auto`instead of `int` ? IIRC, variable live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway. Please do correct me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:14:10.443",
"Id": "66071",
"Score": "0",
"body": "this is a C++11 feature: `auto` means that the type will be deduced from the initalizer. E.g. `auto i = 1;` will give `i` the type of `int`. The old `auto` keyword from C has been deprecated. If you cannot use C++11, just replace `auto` with `int` everywhere in the above code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:15:42.787",
"Id": "66079",
"Score": "0",
"body": "Thanks for clarifying. Another question: how is separate functions is faster over nested loop, in this case mine. I see you called in between functions. If my question has been asked before, please cite the source here. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:59:24.410",
"Id": "66086",
"Score": "1",
"body": "@vincentChen my advice is to first code for clarity, then for speed. A separate function that returns by value instead of modifying a reference, makes the code easier to reason about. It is also easier to test a small function that does only thing. You can use such small functions as building blocks for larger algorithms. You shouldn't worry too much about function call overhead. The compiler is likely to inline it anyway when given a suitable optimization flag."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:49:26.057",
"Id": "39384",
"ParentId": "39373",
"Score": "3"
}
},
{
"body": "<p>If you'd like it even faster consider this:</p>\n<pre><code>#include <math.h>\n#include <iostream>\n#include <chrono>\n\nusing namespace std;\n\nint TR_triangle(int n)\n{\n return ((n + 1) * n) / 2;\n}\n\n// Math fact: a prime decomposition n = Prod_i p_i^e_i yields\n// Prod_i (e_i + 1) different divisors\nint TR_num_divisors(int n)\n{\n auto divisors = 1; // 1 has one divisor\n {\n auto f = 2;\n auto count = 0;\n while (n % f == 0) {\n ++count;\n n /= f; // divide by factor of 2\n }\n divisors *= (count + 1);\n }\n\n // <= n guarantees that a prime has 2 divisors\n for (auto f = 3; f <= n; f += 2) {\n auto count = 0;\n while (n % f == 0) {\n ++count;\n n /= f; // divide by odd factor\n }\n divisors *= (count + 1);\n }\n return divisors;\n}\n\nint TR_unique_divisors(int n)\n{\n if (n % 2 == 0)\n n /= 2;\n return TR_num_divisors(n);\n}\n\n// triangle(n) = (n + 1) * n / 2\n// only one of them has a factor of two, and they have no prime factors in common\n// we can cache one of the divisor counts while iterating over triangle numbers\nint TR_first_triangle_with_more_than_n_divisors(int n)\n{\n auto i = 1;\n for (auto f1 = TR_unique_divisors(i), f2 = TR_unique_divisors(i + 1); f1 * f2 <= n; ++i) {\n f1 = f2; // re-use result from previous iteration\n f2 = TR_unique_divisors(i + 2); // only one new computation\n }\n return i;\n}\nint* TIN_ESieve(int upperLimit)\n{\n int sieveBound = (int)(upperLimit - 1) / 2;\n int upperSqrt = (int)((sqrt((double)upperLimit) - 1) / 2);\n bool PrimeBits[1000] = {false};\n int* numbers = new int[1000];\n int index = 0;\n for(int i = 2; i <= upperSqrt; i++)\n {\n if(!PrimeBits[i])\n {\n for(int j = i * i; j <= sieveBound; j += i)\n {\n PrimeBits[j] = true;\n }\n numbers[index++] = i;\n }\n }\n for(int i = upperSqrt + 1; i <= sieveBound; i++)\n {\n if(!PrimeBits[i])\n {\n numbers[index++] = i;\n }\n }\n numbers[index] = 0;\n return numbers;\n}\nint TIN_PrimeFactorisationNoD(int number, int primelist[])\n{\n int nod = 1;\n int exponent;\n int remain = number;\n\n for(int i = 0; primelist[i] != 0; i++)\n {\n\n // In case there is a remainder this is a prime factor as well\n // The exponent of that factor is 1\n if(primelist[i] * primelist[i] > number)\n {\n return nod * 2;\n }\n\n exponent = 1;\n while(remain % primelist[i] == 0)\n {\n exponent++;\n remain = remain / primelist[i];\n }\n nod *= exponent;\n\n //If there is no remainder, return the count\n if(remain == 1)\n {\n return nod;\n }\n }\n return nod;\n}\nint main()\n{\n auto start = chrono::steady_clock::now();\n for(int c1 = 1; c1 <=10; c1++)\n {\n auto sieve = TIN_ESieve(1000);\n int i1 = 2;\n int cnt = 0;\n int Dn1 = 2;\n int Dn = 2;\n while(cnt < 500)\n {\n if(i1 % 2 == 0)\n {\n Dn = TIN_PrimeFactorisationNoD(i1 + 1, sieve);\n }\n else\n {\n Dn1 = TIN_PrimeFactorisationNoD((i1 + 1) / 2, sieve);\n }\n cnt = Dn * Dn1;\n i1++;\n }\n if(c1 == 1)\n cout << "the first Triangle number to have over " << 500 << " divisors : " << i1 * (i1 - 1) / 2 << "\\n";\n }\n auto stop = chrono::steady_clock::now();\n auto elapsed = chrono::duration_cast<std::chrono::milliseconds>((stop - start)/10);\n\n cout << "\\nUsing TIN methods it averaged " << elapsed.count() << " milliseconds." << "\\n\\n";\n start = chrono::steady_clock::now();\n for(int c2 = 1; c2 <= 10; c2++)\n {\n auto const n = 500;\n auto res = TR_triangle(TR_first_triangle_with_more_than_n_divisors(n));\n if(c2 == 1)\n std::cout << "the first Triangle number to have over " << n << " divisors : " << res << "\\n";\n }\n stop = chrono::steady_clock::now();\n elapsed = chrono::duration_cast<std::chrono::milliseconds>((stop - start) /10);\n\n cout << "\\nUsing TR methods it averaged " << elapsed.count() << " milliseconds." << "\\n";\n return 0;\n}\n</code></pre>\n<p>This <a href=\"http://coliru.stacked-crooked.com/a/cc77df74f1645834\" rel=\"nofollow noreferrer\">Live Example</a> compares the 2 with a significant difference in execution times.</p>\n<p>This was ported from a C# method I found. I can't remember where though. My apologies to the originator.</p>\n<p>The sieve, based on the Sieve of Eratosthenes, basically uses an array of booleans initialized to false. You start with the first prime,2, and change every successive boolean that's a multiple to true. Repeat with every element that is false when the loop gets there. When the loop is done, the index of every element that is false is a prime. What I've done is added an optimization and added the primes to the list in the main loop then used another loop that starts where that one left off. The trick is to use booleans so that you're only checking true/false instead of decoding an integer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:06:25.813",
"Id": "65986",
"Score": "0",
"body": "Upvoted, such algorithmic optimizations are what Project Euler is all about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T10:36:14.493",
"Id": "66276",
"Score": "0",
"body": "very complicated, I wrapped my head around for a day now, still can't understand how you averaging the result. And how the TIN sieve works? what is the mathematical concept behind it? Thanks for answering my question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T03:20:12.720",
"Id": "66366",
"Score": "0",
"body": "I added a simple explanation for you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:27:52.763",
"Id": "39407",
"ParentId": "39373",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T10:33:04.183",
"Id": "39373",
"Score": "6",
"Tags": [
"c++",
"optimization",
"algorithm",
"c++11",
"programming-challenge"
],
"Title": "Project Euler #12 - highly divisible triangular number"
}
|
39373
|
<p>I needed smth that could send (scp/rsync) many files in parallel <em>but that would not overload machine, firewalls on the way by starting e.g. 600 simultaneous uploads</em>, so upload should be done in batches. </p>
<p>Most of the utilities like <code>aria2c</code> are <em>download</em> managers and I needed something to send many files in parallel from a machine behind NAT to a machine on the internet (so no dl from internet possible).</p>
<p>Pls keep in mind that it's the draft that I quote below, I do not need details on general good practices such as setting paths and counters using variables and not literal values.</p>
<p>Any better approach? Problems? I've noticed that I have to <code>sleep 1</code> between starting scp cmds in background or else target server refuses some connections.</p>
<pre><code>#!/bin/bash
FLIST=file_paths_list.txt
COUNTER=0
PIDS=()
cat ${FLIST} | while read F; do
COUNTER=$((COUNTER + 1))
echo COUNTER $COUNTER
sleep 1
scp ${F} root@host:/data/tmp &
PID=$!
echo Adding PID $PID
PIDS+=($PID)
if [ $COUNTER -lt 20 ]; then
continue
fi
# wait for uploads batch to complete
for PID in ${PIDS[@]}; do
echo waiting for PID $PID
wait $PID
done
# reset PIDS array
PIDS=()
COUNTER=0
done
</code></pre>
|
[] |
[
{
"body": "<p>The best code would be no code at all.</p>\n\n<p>Using <a href=\"http://www.openbsd.org/cgi-bin/man.cgi?query=sftp&sektion=1\" rel=\"nofollow\"><code>sftp(1)</code></a> with the <code>-R</code> <em>num_requests</em> option (and/or <code>-l</code> <em>bandwidth_limit</em>), you can do a <code>put</code> of multiple files simultaneously.</p>\n\n<p>Alternatively, use a client such as <a href=\"http://lftp.yar.ru/lftp-man.html\" rel=\"nofollow\"><code>lftp(1)</code></a> that specializes in batch operations, and has robustness-enhancing features like automatic retry. To do parallel uploads, use <code>lftp -e 'mirror --reverse --parallel'</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T10:31:21.740",
"Id": "66078",
"Score": "0",
"body": "Sadly, I have seen only modest speedup (30%-50%) with using `-R` option for `sftp` (which they even say in manpage IIRC), because those are outstanding requests that are parallelized, not separate connections it seems. Have to try `lftp` though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T12:37:48.737",
"Id": "39381",
"ParentId": "39377",
"Score": "3"
}
},
{
"body": "<p>It is very, very unlikely that running multiple files in parallel will go any faster than running them all sequentially (your bottleneck will be 'internet' bandwidth regardless).</p>\n\n<p>Is there something wrong with doing something like:</p>\n\n<pre><code>#!/bin/bash\n\nSCPCMD=\"scp \\\"\\$@\\\" root@host:/data/tmp\"\n# echo The scp command is: $SCPCMD\n\ncat ${FLIST} | tr '\\n' '\\000' | xargs --null bash -c \"${SCPCMD}\"\n</code></pre>\n\n<p>The above script will convert newlines to null characters in the input list, then copy the files to the server.</p>\n\n<p>You can add the <code>-n 10</code> argument to xargs to do 10 files are a time, or whatever works for you. I like the -t argument as well which echos the xarg command to stderr before it runs it.</p>\n\n<p>The above will copy only one stream at a time, but, it will do the files in bulk operations, and you will likely be limited by your network bandwidth, not the parallelism of your copies. </p>\n\n<h2>EDIT:</h2>\n\n<p>If you want to run the scp's in parallel, you can add the <code>-P xx</code> (<code>--max-procs</code>)argument to xargs, which will run as many as <code>xx</code> scp's in parallel for you. So, for example, if you have hundreds of files, you can scp them in 5 parallel streams, 5 files at a time, with:</p>\n\n<pre><code>cat ${FLIST} | tr '\\n' '\\000' | xargs --null -P 5 -n 5 bash -c \"${SCPCMD}\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:49:29.720",
"Id": "65912",
"Score": "0",
"body": "It is very much likely that they will be faster in parallel bc I have demonstrable evidence that they do: it seems that many companies, ISPs etc implement some sort of load balancing anyway, and even inside the companies: at mine the network admins do some magic that cause my scp of a single file max out at 10-20 MB/s which makes the same set of files use up 5 hrs to complete sending while the script I posted sends it in less than 30 mins. In principle all that you have to do is tracking tcp/ip connections which stateful firewalls do anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:53:21.833",
"Id": "65913",
"Score": "0",
"body": "Of course if you have low bw ADSL uplink you can saturate it with sequential upload as well. But once your data leaves \"last mile\" the ISPs do stuff to your connections. A friend of mine is sending 400GB of physics data today to US from Europe and sees rsync speed vary from 10 KB/s to 20 MB/s from moment to moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:59:47.067",
"Id": "65915",
"Score": "0",
"body": "I can see where multi-link protocols over the net could help with bandwidth... 200's answer is probably closer to the mark - using the right tools for the job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T15:04:04.507",
"Id": "65917",
"Score": "0",
"body": "nevertheless the trick with `-n` argument to `xargs` is a very nice one which is why I upvoted your answer, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T17:08:26.620",
"Id": "65947",
"Score": "0",
"body": "@JohnDoe - xargs can run things in parallel too ;-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:24:54.487",
"Id": "39383",
"ParentId": "39377",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39383",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T11:48:06.323",
"Id": "39377",
"Score": "4",
"Tags": [
"bash",
"shell"
],
"Title": "Parallelizing upload"
}
|
39377
|
<p>The following code works and does what I want, but I'd like to confirm I'm using this OOP concept correctly. I'm using the following class to get and set some configuration parameters for my program. It used $GLOBALS for this before, but I'm trying to use a singleton pattern for this instead.</p>
<p>Below is the Config class. Does anything jump out as aggressively stupid? Seeing as how I'm going to be including this in most files any way I figured it would make sense to throw the autoload function in there too- is this bad design?</p>
<pre><code><?php
//This class will be included for every file
//needing access to global settings and or
//the class library
spl_autoload_register(function($class){
require_once 'classes/' . $class . '.php';
});
final class Config {
private static $inst = null;
//Array to hold global settings
private static $config = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '123456',
'db' => NULL
),
'shell' => array(
'exe' => 'powershell.exe',
'args' => array(
'-NonInteractive',
'-NoProfile',
'-NoLogo',
'-Command'
)
)
);
public static function getInstance() {
if (static::$inst === null) {
static::$inst = new Config();
}
return static::$inst;
}
public function get($path=NULL) {
if($path) {
//parse path to return config
$path = explode('/', $path);
foreach($path as $element) {
if(isset(static::$config[$element])) {
static::$config = static::$config[$element];
} else {
//If specified path not exist
static::$config = false;
}
}
}
//return all configs if path NULL
return static::$config;
}
public function set($path=NULL,$value=NULL) {
if($path) {
//parse path to return config
$path = explode('/', $path);
//Modify global settings
$setting =& static::$config;
foreach($path as $element) {
$setting =& $setting[$element];
}
$setting = $value;
}
}
//Override to prevent duplicate instance
private function __construct() {}
private function __clone() {}
private function __wakeup() {}
}
</code></pre>
<p>I access it like so:</p>
<pre><code>$aaa = Config::getInstance();
var_dump($aaa->get());
$aaa->set('mysql/host','zzzzzzzzzzzz');
var_dump($aaa->get());
</code></pre>
<p>I read a little bit about how singletons are less useful in php. I will research that further at some point, but for the time being I just want to make sure I'm doing this right.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:39:19.657",
"Id": "65994",
"Score": "1",
"body": "The question you really need to ask is: Would a second Config cause the death of the app? Not just confusion... would the app fall apart if a second instance ever existed, even if the app never knew about it? If it wouldn't, then don't make the class a Singleton. If you want a global, then use a global; Singleton doesn't make that any less evil. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:05:16.830",
"Id": "65996",
"Score": "0",
"body": "Well I will admit it was simpler when I used $GLOBALS. I should have come clean before, but I don't even know what this mostly hypothetical app will do. For learning purposes I wanted to pretend that I needed a single instance of the config so I could learn how to implement that. Assuming I do need a singleton because a second config _would_ cause the death of the app, is the code acceptable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:08:02.250",
"Id": "65997",
"Score": "0",
"body": "Oh also, is it ok to throw the autoload function in this class? I was afraid it might be bad\\sloppy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:39:14.347",
"Id": "66015",
"Score": "0",
"body": "It's not bad, but i imagine there's a better place for it..."
}
] |
[
{
"body": "<p>There should be something about a Singleton class that <em>requires</em> that it allow and present a <em>single</em>, <em>globally available</em>, <em>instance</em>. Otherwise, the pattern is being misused.</p>\n\n<p>The way your class is built, there's not really such a reason. You could have any number of instances, and they'd all work (though they'd all look like the same instance anyway).</p>\n\n<p>As for recommendations to make things less weird...?</p>\n\n<ul>\n<li><p><strong>Use instance variables.</strong></p>\n\n<p>Everything is essentially global. (Make no mistake; hiding it in a class doesn't do much at all to change that. <code>static</code> is just how a lot of OO languages spell \"global\". :P) Your \"instance\" is just an interface to get and set that global stuff. Every \"instance\" has the same ability, since it gets and sets the same variables -- and in fact, any update through one \"instance\" will be reflected in every other. So <code>new Config</code> and <code>Config::getInstance()</code> really differ only in whether another instance is created. The caller could say one or the other, and get the exact same results.</p>\n\n<p>If you insist on a singleton, moving the <code>static</code> variables into the instance would legitimize the existence of an instance at all, and provide a less dodgy reason to require exactly one authoritative instance. (Though it'd also prompt the question, \"Why can't i create a separate configuration for testing?\". Among others.)</p></li>\n<li><p><strong>Lose the public setter, or provide a way to disable it.</strong></p>\n\n<p>There's next to no encapsulation or data hiding going on here; the only thing that even remotely counts is your path stuff. Any caller can change global settings at will. This kind of \"action at a distance\" can cause all kinds of weirdness. It is the very reason mutable global state is discouraged, and <code>set</code> makes it even easier to abuse.</p>\n\n<p>You should consider either getting rid of the setter, making it private (and thus disabling outside modification altogteher), or adding some way for your setup code to disable it -- effectively \"freezing\" the instance -- once the configuration is established.</p></li>\n<li><p><strong>Use <code>self::</code>, not <code>static::</code>.</strong></p>\n\n<p><code>static</code> (when used in place of a class name) uses PHP's \"late static binding\" to look up variables through the name of the called class rather than the one where the method lives. It's there to allow subclasses to override static members. But you've explicitly disallowed inheritance...so values will only ever be looked up in this class. <code>static</code> is thus wasteful, and a bit of a mixed message.</p></li>\n<li><p>As for the autoloader, it's not exactly a mortal sin or anything to put that in the same file as the config class. Unless the classes are going to be moving around, though, their current location isn't really part of the config settings, is it?</p>\n\n<p>I'd suggest making the autoloader a part of the startup code, unless the class files are going to move around (thus making the current location a part of the configuration).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:29:38.940",
"Id": "66110",
"Score": "0",
"body": "Thanks for all the great info. I thought that static replaced self and that the behavior of self was a flaw not a feature. Is it wrong to just always use static or are there performance considerations? If declare a class final shouldn't that clear up any confusion? It would just be nice to only have one keyword for this instead of juggling two. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:24:47.203",
"Id": "66164",
"Score": "2",
"body": "It *can* be wrong to use `static::`. If you have class B that extends class A, and `A::method` uses `static::$stuff`, then `B::method()` will first look for `B::$stuff`, *then* `A::$stuff`. Sometimes you don't want that. In your current case, \"wrong\" is a bit of an overstatement. But the whole point of `static::` is to cause LSB, so it is really better used only when you (1) can have subclasses, and (2) want them to be able to override a static attribute. LSB implies extensibility, which contradicts the one line (more than a screen away from most uses of it) that outlaws extension."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:38:49.747",
"Id": "66179",
"Score": "0",
"body": "The difference between `self` vs `static` is important, and sometimes quite desirable -- particularly if you have some functionality you don't want overridden, or want to be certain of where you're setting a variable but don't want to hard-code the class name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:46:43.830",
"Id": "66184",
"Score": "0",
"body": "Thanks for the great explanation, that makes sense to me now. So self can be useful if I am extending a class, but also want to access a method in the parent instead of the local instance of that method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T18:29:58.877",
"Id": "67553",
"Score": "0",
"body": "Close. (It sounds like you get it, but the wording is a bit off.) `self` is useful whenever you want to specifically use your version of a method. It's used by the parent, not the child. (The child can of course use `self` too, but it will be referring to itself, not the parent.) If you want a child class to use a parent's version of a method, that's what `parent` is for."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:32:15.177",
"Id": "39426",
"ParentId": "39382",
"Score": "5"
}
},
{
"body": "<p>I just want to add to cHao's explanation of <code>static</code> vs <code>self</code>. You use <code>self</code> to call a static function rather than do <code>$this-></code> because you can only do <code>$this</code> if you have instantiated an object. </p>\n\n<p>This is typically done when you want to call a function that belongs to a class but that function has static variables (like a hard coded constant/variable) that is used within the function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T20:28:42.020",
"Id": "44298",
"ParentId": "39382",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39426",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:18:50.937",
"Id": "39382",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"singleton"
],
"Title": "Using a singleton class to get and set program wide settings"
}
|
39382
|
<p>I need your help in OpenCV. I'm a student and am working on a project in which involves a little autonomous car. I use Python for the main programming language.</p>
<p>I have some problem with my meanshift. When I run the program, I want the camera fixed on an area on the floor and stay on this area. I would like for the car to drive alone while following the floor, and I don't want that meanshift to find another object different from the floor.</p>
<p>The program works well, but not optimally for the floor. Do you have a solution or a way to proceed?</p>
<pre><code>def camshift(frame1,frame2,trackWindow) :
points=[]
size1=frame1.shape[0] #width
size2=frame1.shape[1] #length
#hsv referentiel
hsv = cv2.cvtColor(frame1, cv2.COLOR_BGR2HSV)
#Mask
mask = cv2.inRange(hsv,np.array((0., 60.,32.)), np.array((180.,255.,255.)))
x0, y0, w, h = trackWindow
trackWindow1=[x0,y0,w,h]
x1 = x0 + w -1
y1 = y0 + h -1
hsv_roi = hsv[y0:y1, x0:x1]
mask_roi = mask[y0:y1, x0:x1]
#compute histogram for that area
hist = cv2.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
#Normalisation
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX);
hist_flat = hist.reshape(-1)
points.append(hsv)
prob = cv2.calcBackProject([hsv,cv2.cvtColor(frame2, cv.CV_BGR2HSV)],[0],hist_flat, [0,180],1)
prob &= mask
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
#checking conditions not to go out of bounds
if (trackWindow[0] < 0) :
trackWindow[0] = 0
if (trackWindow[1] < 0) :
trackWindow[1] = 0
if (trackWindow[0]+trackWindow[3] >= size1) :
trackWindow1.append(size1-y0)
w=trackWindow1[4]
trackWindow1.pop()
if (trackWindow[0]+trackWindow[2] >= size2) :
trackWindow1.append(size2-x0)
h=trackWindow1[4]
trackWindow1.pop()
x0, y0, w, h = trackWindow
if (trackWindow[0]+trackWindow[2])<100 :
trackWindow = (125,125,200,100)
if (trackWindow[1]+trackWindow[3])<100 :
trackWindow = (125,125,200,100)
# self.ellipse, trackWindow = cv2.CamShift(prob, trackWindow, term_crit)
new_ellipse, track_window = cv2.CamShift(prob,trackWindow, term_crit)
#we draw the rectangle on the relevant area
cv2.rectangle(frame1, (trackWindow[0],trackWindow[1]), (trackWindow[0]+trackWindow[2],trackWindow[1]+trackWindow[3]), color=(255,0,0))
cv2.imshow("mask",mask)
return track_window
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T08:59:48.483",
"Id": "66746",
"Score": "2",
"body": "Hello, and welcome to Code Review! What do you mean by \"not optimally for the floor\"? We focus on improving working code: code reviews will not change the behaviour, only do the same thing in a better way. Sorry if you were misled on Stack Overflow."
}
] |
[
{
"body": "<p>Whitespace. Use it. It makes code <em>much</em> clearer. Here's a list of places where you can add whitespace to make your code clearer.</p>\n\n<ol>\n<li><code>(frame1,frame2,trackWindow) :</code> \\$\\rightarrow\\$ <code>(frame1, frame2, trackWindow):</code></li>\n<li><code>trackWindow1=[x0,y0,w,h]</code> \\$\\rightarrow\\$ <code>trackWindow1 = [x0, y0, w, h]</code></li>\n<li><code>( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )</code> \\$\\rightarrow\\$ <code>(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)</code></li>\n<li><code>cv2.imshow(\"mask\",mask)</code> \\$\\rightarrow\\$ <code>cv2.imshow(\"mask\", mask)</code></li>\n</ol>\n\n<p>There are many other places like this in your code, so I'm going to recommend looking at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>, Python's official style guide, on how to correct these.</p>\n\n<p>Finally, in all your <code>if</code> conditions, are just <code>if</code> conditions. If you're not using <code>elif</code>, then all of these conditions will be evaluated if they are true. Are you sure that you want this?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-05T02:54:37.160",
"Id": "95828",
"ParentId": "39386",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T13:52:32.360",
"Id": "39386",
"Score": "1",
"Tags": [
"python",
"opencv"
],
"Title": "Track a fix area with meanshift -OpenCV"
}
|
39386
|
<p>I create a binary tree, now I want to remove a node. I hope that you can provide me some input. The nodes are composed of characters instead of numbers.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinaryTree
{
public class BinaryTree
{
private BinaryTreeNode root;
public BinaryTree()
{
root = null;
}
public void insert(char c)
{
addNode(c, ref root);
}
private void addNode(char c, ref BinaryTreeNode rptr)
{
if (rptr == null)
rptr = new BinaryTreeNode(c);
else if (rptr.left == null)
addNode(c, ref rptr.left);
else if (rptr.right == null)
addNode(c, ref rptr.right);
else
addNode(c, ref rptr.left);
}
public void inOrderTraversal()
{
inOrderTraversalHelper(root);
}
private void inOrderTraversalHelper(BinaryTreeNode r)
{
if (r != null)
{
inOrderTraversalHelper(r.left);
Console.Write("{0} ", r.id);
inOrderTraversalHelper(r.right);
}
}
public void preOrderTraversal()
{
preOrderTraversalHelper(root);
}
private void preOrderTraversalHelper(BinaryTreeNode r)
{
if (r != null)
{
Console.Write("{0} ", r.id);
preOrderTraversalHelper(r.left);
preOrderTraversalHelper(r.right);
}
}
public void postOrderTraversal()
{
postOrderTraversalHelper(root);
}
private void postOrderTraversalHelper(BinaryTreeNode r)
{
if (r != null)
{
postOrderTraversalHelper(r.left);
postOrderTraversalHelper(r.right);
Console.Write("{0} ", r.id);
}
}
public void removeNode(char c)
{
deleteNode(c, ref root);
}
private void deleteNode(char c, ref BinaryTreeNode root)
{
if (root == null)
{ }
else
{
if (root.left.id != c)
{
deleteNode(c, ref root.left);
}
else if (root.right.id != c)
{
deleteNode(c, ref root.right);
}
else if (root.left.id == c)
{
root.left = root.left.left;
}
else if(root.right.id == c)
{
root.right = root.right.right;
}
}
}
}
public class BinaryTreeNode
{
public char id { get; set; }
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode()
{
left = right = null;
}
public BinaryTreeNode(char _id)
{
id = _id;
left = right = null;
}
}
}
</code></pre>
<p>The main program is:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinaryTree
{
class Program
{
static void Main(string[] args)
{
BinaryTree b = new BinaryTree();
b.insert('A');
b.insert('B');
b.insert('C');
b.insert('D');
b.insert('E');
b.insert('G');
b.insert('H');
b.insert('F');
b.insert('J');
b.insert('K');
b.insert('L');
Console.WriteLine("The Inorder Traversal:\n");
b.inOrderTraversal();
Console.WriteLine("\n\nThe Preorder Traversal:\n");
b.preOrderTraversal();
Console.WriteLine("\n\nThe Postorder Traversal:\n");
b.postOrderTraversal();
b.removeNode('F');
b.inOrderTraversal();
Console.WriteLine("The Inorder Traversal after delete a node:\n");
Console.WriteLine();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:29:14.413",
"Id": "65908",
"Score": "0",
"body": "When you find the node you want to delete, your code saves either the left or right subtree below it. You'll need to do a little more work to save both subtrees."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:30:26.370",
"Id": "65909",
"Score": "1",
"body": "In C# the naming convention for methods is PascalCase."
}
] |
[
{
"body": "<p>A few points:</p>\n\n<ol>\n<li><p>Your code for both searching for the node to be removed and for removing it is broken. @HABO pointed out the second part of this. You need to check both halves of the tree for the node. Then, if you find it and delete it, you have to combine both its child subtrees into a new subtree which will be appended at this position. This involves something called 'rotating' the tree - you have to decide which of <code>left</code> and <code>right</code> becomes the new head of the subtree.</p></li>\n<li><p>As you currently construct it, new nodes will almost always be inserted into the 'left' side of the tree. This means that your tree will be very far from being 'balanced'. In fact it will look something like a linked list, with a depth almost as big as the number of nodes in the tree. Balance is important in trees - some operations take longer, the more steps away from the root your nodes are. The better balanced the tree, the fewer steps there will be. There are various clever ways of guaranteeing that trees will be more or less balanced all the time. But if you just inserted new nodes randomly to the left or right, you would do a lot better most of the time.</p></li>\n<li><p>Rather than implement each of your methods by calling a method in <code>BinaryTree</code> with a <code>BinaryTreeNode</code> <code>ref</code> argument, why don't you make these methods members of <code>BinaryTreeNode</code>? This would make the code a lot simpler. You should find that you can do nice things like check if the root is to be deleted, and if not call the same <code>deleteNode</code> function for both <code>left</code> and <code>right</code>. Same for traversal. If you do this right, you might only need one class instead of two.</p></li>\n</ol>\n\n<p>I don't know if you are trying to solve a specific problem or just learn about data structures, but you might want to look up some literature on data structures and the standard ways of doing insertions, searches, etc. for various types of tree and other structure. If you can, find a book that is specific to C# or Java. Older books for C++ or other languages often have to use more complicated ways of expressing the structures based on pointers. If you learn to do this stuff nicely with a language like C# you will avoid doing things like passing ref arguments in and out when it's not strictly needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T16:29:04.843",
"Id": "39396",
"ParentId": "39388",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39396",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:20:58.383",
"Id": "39388",
"Score": "2",
"Tags": [
"c#",
"algorithm"
],
"Title": "Delete a node from a binary tree"
}
|
39388
|
<p>This is a continuation of this:
<a href="https://codereview.stackexchange.com/questions/39197/performance-of-biginteger-square-root-and-cube-root-functions-in-java">Performance of BigInteger square root and cube root functions in Java</a></p>
<p>I've made most of the changes suggested, but since I'm loading literally the largest array possible on the computer, I'd like some review before I implement Sieve of Atkin.</p>
<p>Code follows, just over 300 lines, formatted by Netbeans <kbd>ALT</kbd>-<kbd>SHIFT</kbd>-<kbd>F</kbd> function.</p>
<pre><code>package pfactor;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Factor {
static BigInteger number;
static BigInteger sqrt;
static BigInteger cbrt;
static boolean abbrev;
static final BigInteger TWO = new BigInteger("2");
static final BigInteger THREE = new BigInteger("3");
static int[] arrayData;
static BigInteger pArray;
public static void main(String[] args) {
LoadSysData();
abbrev = ask("Do you want to abbreviate numbers? ");
try {
number = new BigInteger(getFile());
} catch (IOException ex) {
System.out.println("Error: File not found");;
}
System.out.println("Factoring: \n\n" + abbreviate(number));
sqrt = sqrt(number);
System.out.println("The square root is: " + abbreviate(sqrt));
BigInteger testNum = sqrt.multiply(sqrt);
System.out.println("Difference: " + abbreviate(number.subtract(testNum).abs()));
System.out.println("Check returns: " + checksqrt());
cbrt = cbrt(number);
testNum = cbrt.multiply(cbrt).multiply(cbrt);
System.out.println("The cube root is: " + abbreviate(cbrt));
System.out.println("Difference: " + abbreviate(number.subtract(testNum).abs()));
System.out.println("Check returns: " + checksqrt());
testNum = sqrt.subtract(cbrt);
System.out.println("Search size: " + abbreviate(testNum));
arrayData = getLargestArray();
System.out.println("Prime stats determined at " + arrayData[0] + " dimension(s) of size(s) " + getArrayData());
System.out.println(FreeRAM() + " of RAM remaining.");
System.out.println("Beginning prime load...\tExpect heavy RAM/CPU usage.");
IntializeArray();
System.out.println(FreeRAM() + " of RAM remaining.");
}
public static String getFile() throws IOException {
Scanner scanner = new Scanner(new File("Number.dat"));
StringBuilder content = new StringBuilder();
while (scanner.hasNextLine()) {
content.append(scanner.nextLine());
}
return content.toString();
}
public static BigInteger sqrt(BigInteger n) {
BigInteger guess = n.divide(BigInteger.valueOf((long) n.bitLength() / 2));
boolean go = true;
int c = 0;
BigInteger test = guess;
while (go) {
BigInteger numOne = guess.divide(TWO);
BigInteger numTwo = n.divide(guess.multiply(TWO));
guess = numOne.add(numTwo);
if (numOne.equals(numTwo)) {
go = false;
}
if (guess.mod(TWO).equals(BigInteger.ONE)) {
guess = guess.add(BigInteger.ONE);
}
//System.out.println(guess.toString());
c++;
c %= 5;
if (c == 4 && (test.equals(guess))) {
return guess;
}
if (c == 2) {
test = guess;
}
}
if ((guess.multiply(guess)).equals(number)) {
return guess;
}
return guess.add(BigInteger.ONE);
}
public static BigInteger cbrt(BigInteger n) {
BigInteger guess = n.divide(BigInteger.valueOf((long) n.bitLength() / 3));
boolean go = true;
int c = 0;
BigInteger test = guess;
while (go) {
BigInteger numOne = n.divide(guess.multiply(guess));
BigInteger numTwo = guess.multiply(TWO);
guess = numOne.add(numTwo).divide(THREE);
if (numOne.equals(numTwo)) {
go = false;
}
if (guess.mod(TWO).equals(BigInteger.ONE)) {
guess = guess.add(BigInteger.ONE);
}
//System.out.println(guess.toString());
c++;
c %= 5;
if (c == 4 && (test.equals(guess))) {
return guess;
}
if (c == 2) {
test = guess;
}
if (c == 3) {
guess = guess.add(BigInteger.ONE);
}
}
if ((guess.multiply(guess)).equals(number)) {
return guess;
}
return guess.add(BigInteger.ONE);
}
public static int[] getLargestArray() {
ArrayList<Object> test = new ArrayList<Object>();
int x = 1, y = 1, z = 1, a = 1, b = 1;
int scale = 100000;
int d = 1;
boolean go = true;
while (go) {
try {
switch (d) {
case 1:
test.add(new BigInteger[x]);
x += scale;
break;
case 2:
test.add(new BigInteger[x][y]);
y += scale;
break;
case 3:
test.add(new BigInteger[x][y][z]);
z += scale;
break;
case 4:
test.add(new BigInteger[x][y][z][a]);
a += scale;
break;
case 5:
test.add(new BigInteger[x][y][z][a][b]);
b += scale;
break;
default:
test.add(new BigInteger[x]);
}
if (x == Integer.MAX_VALUE) {
d++;
}
if (y == Integer.MAX_VALUE) {
d++;
}
if (z == Integer.MAX_VALUE) {
d++;
}
if (a == Integer.MAX_VALUE) {
d++;
}
if (b == Integer.MAX_VALUE) {
d++;
}
test.clear();
} catch (OutOfMemoryError e) {
scale %= 10;
//System.out.println(d + " " + scale + " " + x);
} catch (Exception e) {
e.printStackTrace();
}
if (scale == 0) {
go = false;
}
}
int[] results = new int[6];
results[0] = d;
results[1] = x;
results[2] = y;
results[3] = z;
results[4] = a;
results[5] = b;
return results;
}
public static boolean checksqrt() {
if ((sqrt.multiply(sqrt)).equals(number)) {
return true;
}
BigInteger margin = number.subtract((sqrt.multiply(sqrt))).abs();
BigInteger maxError = (sqrt.subtract(BigInteger.ONE)).multiply(TWO);
if (margin.compareTo(maxError) == -1) {
return true;
}
return false;
}
public static boolean checkcbrt() {
if ((cbrt.multiply(cbrt).multiply(cbrt)).equals(number)) {
return true;
}
BigInteger margin = number.subtract((cbrt.multiply(cbrt).multiply(cbrt))).abs();
BigInteger c = cbrt.subtract(BigInteger.ONE);
BigInteger maxError = ((c.multiply(c)).multiply(THREE)).add(c.multiply(THREE));
if (margin.compareTo(maxError) == -1) {
return true;
}
return false;
}
public static String abbreviate(BigInteger n) {
if (n.toString().length() < 7) {
return n.toString();
}
if (abbrev) {
return n.toString().substring(0, 3) + "..." + n.mod(new BigInteger("1000")) + "(" + n.toString().length() + " digits)";
}
return n.toString();
}
public static boolean ask(String prompt) {
Scanner s = new Scanner(System.in);
System.out.println(prompt + "(Y/N)");
String input = s.nextLine();
char c;
if (input.length() != 0) {
c = input.charAt(0);
} else {
return ask("");
}
if (c == 'N' || c == 'n') {
return false;
}
if (c == 'Y' || c == 'y') {
return true;
}
return ask("");
}
public static String getArrayData() {
String result = "";
for (int i = 0; i < arrayData[0]; i++) {
result = result += arrayData[i + 1] + ",";
}
return result.substring(0, result.length() - 2);
}
public static String FreeRAM() {
long bytes = Runtime.getRuntime().freeMemory();
if (bytes > 1073741823) {
return String.format("%.4f GB", (bytes / 1073741824.0));
}
if (bytes > 1048575) {
return String.format("%.4f MB", (bytes / 1048576.0));
}
if (bytes > 1023) {
return String.format("%.4f KB", (bytes / 1024.0));
}
return bytes + " bytes";
}
public static void IntializeArray() {
switch (arrayData[0]) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
}
//Figure out way to assign n-dimensional array to a static object
}
public static void LoadSysData() {
System.out.println(FreeRAM());
System.out.println("Number of cores: " + Runtime.getRuntime().availableProcessors());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is only a form/style review and not algorithm review, as I don't really know what some of your algorithms are supposed to do.\nThere are some changes that I would do in your code.</p>\n\n<p>The first one would be replace the <code>while</code> loops for <code>do while</code> loops, and get rid of the flag go. In case of <code>sqrt</code> this would be something like:</p>\n\n<pre><code>do{\n BigInteger numOne = guess.divide(TWO);\n BigInteger numTwo = n.divide(guess.multiply(TWO));\n guess = numOne.add(numTwo);\n if (guess.mod(TWO).equals(BigInteger.ONE)) {\n guess = guess.add(BigInteger.ONE);\n }\n //System.out.println(guess.toString());\n c++;\n c %= 5;\n if (c == 4 && test.equals(guess)) {\n return guess;\n }\n if (c == 2) {\n test = guess;\n }\n}while(!numOne.equals(numTwo));\n</code></pre>\n\n<p>The same goes for <code>cbrt</code> and <code>getLargestArray</code>.</p>\n\n<p>In <code>getLargestArray</code> I would create the result array at the beginning and accumulate the results there. By doing that I could use a <code>for</code> statement and get rid of your 5 <code>ifs</code>. like:</p>\n\n<pre><code>ArrayList<Object> test = new ArrayList<Object>();\nint[] results = new int[6]{1,1,1,1,1,1}; //d x y z a b\n//map the variables as indexes in results for readability!\nint d = 0, x = 1, y = 2, z = 3, a = 4, b = 5;\nint scale = 100000;\ndo {\n try {\n switch (results[d]) {\n\n case 1:\n test.add(new BigInteger[results[x]]);\n results[x] += scale;\n break;\n //other cases...\n default:\n test.add(new BigInteger[results[x]]);\n\n }\n for(int i = x; i < results.lenght; ++i){\n //I doubt that this condition will ever be true, and also that this is what you really want to check, but I follow the algorithm as yours\n if(results[i] == Integer.MAX_VALUE){\n results[d]+=1;\n }\n }\n test.clear();\n } catch (OutOfMemoryError e) {\n scale %= 10;\n //System.out.println(d + \" \" + scale + \" \" + x);\n } catch (Exception e) {\n e.printStackTrace();\n }\n}while(scale != 0);\nreturn results;\n</code></pre>\n\n<p>Also take note that a n-dimensional array is just a abstraction for a 1 dimensional contiguous array, and that should be no major differences in your results.</p>\n\n<p>I would also get rid of your magic constants in <code>FreeRam</code>. Write <code>1024 * 1024 * 1024</code> instead of <code>1073741824</code> etc. If you need that the value produced is a double than you can write 1024.0 * 1024...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:00:07.850",
"Id": "66156",
"Score": "0",
"body": "I have a few questions. 1. Where could I get algorithm review? 2. Wouldn't calculating the value instead of constants be slower, especially if i call FreeRAM() multiple times?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:15:48.850",
"Id": "66160",
"Score": "0",
"body": "To your first question: Somebody that knows more math than me and also have a bit understanding of programming, that may be a user of codereview that are willing to contribute with an answer. To your second question: Actually no, the compiler can evaluate the result of 1024 * 1024 (since it is a constant arithmetic expression) at compile time so it doesn't need to be evaluated at run time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:40:17.843",
"Id": "66180",
"Score": "0",
"body": "If you do not want to rely on the compiler then you can declare some constants in your class with that values, so the expression is only evaluated one time. example: private static final int MEGA = 1024 * 1024;"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:34:05.143",
"Id": "39422",
"ParentId": "39398",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-16T17:19:22.047",
"Id": "39398",
"Score": "5",
"Tags": [
"java",
"array"
],
"Title": "Performance of Large BigInteger square root and cube root functions, and excessively large array"
}
|
39398
|
<p>This seems like a pretty basic question, so bear with me...Say I have two (or many) methods in the same class that need a LINQ to SQL DataContext. Additionally, I am needing the DataContext in other classes as well. Does it make sense to create the new DataContext every time? </p>
<p>Should I be creating this DataContext in a different data access class and then inheriting it on each page? I feel like this is the way it should be done, but I'm still learning LINQ to SQL and just looking for some best practices. Can anyone point me to good examples of this? </p>
<p>Thanks,</p>
<p>Code for reference:</p>
<pre><code>protected void LoadProducts()
{
StoreDataClassesDataContext db = new StoreDataClassesDataContext();
var query = from p in db.Products
select new
{
p.ProductID,
p.Description,
p.Price
};
dgProducts.DataSource = query;
dgProducts.DataBind();
}
protected void LoadSales()
{
StoreDataClassesDataContext db = new StoreDataClassesDataContext();
var query = from s in db.Sales
select new
{
s.SaleID,
s.SaleDate,
s.Total
};
dgSales.DataSource = query;
dgSales.DataBind();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:44:26.327",
"Id": "65968",
"Score": "2",
"body": "You should wrap your context instance inside a `using` block, or manually call `Dispose()` when you're done with it... or are you wiring up your UI directly to your database? ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:49:02.020",
"Id": "65971",
"Score": "2",
"body": "BTW code isn't \"for reference\" on Code Review - code is *what gets reviewed*, it should be at the core of your post, see our [help/on-topic]. Your question is ok, it's just that you seem to provide the code \"for convenience\"; know that showing your code is mandatory for your question to be on-topic. Cheers!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:28:50.303",
"Id": "65979",
"Score": "0",
"body": "Thanks for the quick reply. The \"for reference\" comment was probably just bad wording by me. This is code I have but also indicative of the type of code I am seeing in a few different places."
}
] |
[
{
"body": "<p>I can't make a thorough review <em>right now</em>, but here's a quick fix that should help you structure things up.</p>\n\n<p>What you have is probably working, but you're mixing-up presentation with data concerns. I don't think these methods should be returning <code>void</code>. Picture this:</p>\n\n<pre><code>protected IEnumerable<SalesInfo> LoadSales()\n{\n using (var db = new StoreDataClassesDataContext())\n {\n var result = db.Sales.Select(s => new SalesInfo { \n SaleId = s.SaleID,\n SaleDate = s.SaleDate,\n Total = s.Total })\n .ToList();\n return result;\n }\n}\n</code></pre>\n\n<p>What you get is a bunch of <code>SalesInfo</code> objects that contain your query results. Bind <em>that</em> to your UI instead.</p>\n\n<p>It's probably normal you're re-creating the context everytime, you want these things to be as short-lived as possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:13:14.253",
"Id": "65976",
"Score": "3",
"body": "This is so freakin' important that if everyone would do this it would save me a ton of headache at work right now!! Don't modify instance variables when it makes perfect sense to just return an object!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:33:20.047",
"Id": "65980",
"Score": "0",
"body": "I can see how this makes sense. I am definitely mixing data/UI here. I hadn't been using `using` do to this section from [Jon Skeet's C# in Depth](http://csharpindepth.com/ViewNote.aspx?NoteID=89). I may (likely) misunderstood when/not it was okay to omit `using`. After searching around some more on the topic, it seems that even in the right scenario when you don't **need** the `using` and its auto `dispose()` call, you should probably just do it anyway?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:37:48.173",
"Id": "65982",
"Score": "2",
"body": "@FreeMars correct: with your current code if you wrap it with `using` or call `Dispose()` I believe you'd get some `ObjectDisposedException`, because your UI would be fetching the data... but that is *bad*! Rule of thumb, if it implements `IDisposable`, do everything you can to call that `Dispose()` method as soon as possible."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:59:09.707",
"Id": "39406",
"ParentId": "39404",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "39406",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:42:10.167",
"Id": "39404",
"Score": "7",
"Tags": [
"c#",
"linq-to-sql"
],
"Title": "Redundant DataContext ? - LINQ to SQL"
}
|
39404
|
<p>My application uses a simple Model-View-Presenter architecture and uses the following classes and interface:</p>
<p><strong>Presenter:</strong></p>
<pre><code>public abstract class Presenter<V> {
private V view;
public final void setView(V view) {
this.view = view;
}
protected final V getView() {
return this.view;
}
}
</code></pre>
<p><strong>View</strong></p>
<pre><code>public abstract class View<V, P extends Presenter<V>> implements ViewAdapter<V> {
private final P presenter;
public View(P presenter) {
this.presenter = presenter;
}
protected final P getPresenter() {
return this.presenter;
}
void initialize() {
this.getPresenter().setView(this.asView());
}
}
</code></pre>
<p><strong>ViewAdapter</strong></p>
<pre><code>interface ViewAdapter<T> {
T asView();
}
</code></pre>
<p>The application is then wired up like this:</p>
<ul>
<li>A concrete <code>Presenter</code> is created.</li>
<li>A concrete <code>View</code> is created, passing in the concrete <code>Presenter</code> as a constructor parameter.</li>
<li>The <code>View</code> is initialised. During initialisation, the <code>View</code> calls the <code>asView</code> method to pass a view instance to the presenter.</li>
</ul>
<p>Each concrete presenter in the application is parameterised with a view interface. Each concrete view class implements a view interface and can then pass itself to the presenter during initialisation and it is in this area that I am looking for advice.</p>
<p>The <code>ViewAdapter</code> interface exists solely to allow the concrete view to pass itself to the presenter via the <code>asView</code> method whilst maintaining type safety. My concrete views which derive from the View class are then forced to provide an implementation of the <code>asView</code> method in order to provide a view instance to the presenter that is of the correct type. </p>
<p>Every implementation looks the same:</p>
<pre><code>@Override
public FooView asView() {
return this; // this implements the FooView interface.
}
</code></pre>
<p>All this basically does is force 'this' to implement <code>FooView</code> as I am unable to express something like this:</p>
<pre><code>// Example, not valid code, won't compile!
public abstract class View<V, P extends Presenter<V>> implements V {
}
</code></pre>
<p>Which would allow me to remove the <code>ViewAdapter</code> interface and pass the view to the presenter in the abstract <code>View</code> class like this, removing the redundancy:</p>
<pre><code>void initialize() {
this.getPresenter().setView(this);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:15:58.503",
"Id": "65977",
"Score": "0",
"body": "I'm sure it's possible. We're not here to write code for you. We're just here to review your already existing code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:23:40.597",
"Id": "65978",
"Score": "1",
"body": "1). this is actual code from an application I am writing. I have just stripped out the noise to demonstrate the actual problem. 2). I haven't asked anyone to write this for me. I am asking for guidance on factoring out the redundancy introduced with the `ViewAdapter` interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:35:48.777",
"Id": "65981",
"Score": "0",
"body": "I apologize. I'm stupid! Retracted close vote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:23:23.393",
"Id": "66000",
"Score": "1",
"body": "try to use java generics constraints as `Presenter<V extends View>`"
}
] |
[
{
"body": "<p>I tried it in an IDE and have some addition to the last comment. I agree that you should try </p>\n\n<pre><code>Presenter<V extends View>\n</code></pre>\n\n<p>plus I would add that you need to switch the signature to </p>\n\n<pre><code>public abstract class View<V, P extends Presenter> \n</code></pre>\n\n<p>from </p>\n\n<pre><code>public abstract class View<V, P extends Presenter<V>>\n</code></pre>\n\n<p>That is regarding to make it compile. Additionally, you can discard generics V since it is not used anymore in the View so the final signature would be:</p>\n\n<pre><code>public abstract class View<P extends Presenter>\n</code></pre>\n\n<p>Then you can get rid of ViewAdapter and the initialize method should work as you want it:</p>\n\n<pre><code>void initialize() {\n this.getPresenter().setView(this);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T11:27:17.267",
"Id": "40662",
"ParentId": "39405",
"Score": "1"
}
},
{
"body": "<p>After reviewing this code a few times I've come to the conclusion that there is no way to express what I am trying to say in Java I.E the View class must implement an interface of type V as in the (illegal) snippet below.</p>\n\n<pre><code>public abstract class View<V, P extends Presenter<V>> implements V {\n}\n</code></pre>\n\n<p>This leaves me with the following options:</p>\n\n<ol>\n<li>Leave my code as is and accept the (minimal) redundancy.</li>\n<li>Remove some of the generic parameters and accept that if I configure my application incorrectly I will get an invalid cast exception.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T13:41:16.537",
"Id": "46456",
"ParentId": "39405",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "46456",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:56:14.737",
"Id": "39405",
"Score": "5",
"Tags": [
"java"
],
"Title": "Refactoring my simple model-view-presenter architecture"
}
|
39405
|
<p>In MATLAB I have a set of 5393280 points in the form of a decimal-valued vector (x,y,z). How do I represent them in a way that I can quickly collect all the points within some rectangular x-y domain?</p>
<p>Right now I'm representing them as a 3-column matrix, sorted by x-values, and using the following code to extract a rectangular region:</p>
<pre><code>mtx_region = mtx_pointList( dxLowerBound < mtx_pointList(:,1) & ...
dxUpperBound > mtx_pointList(:,1) & ...
dyLowerBound < mtx_pointList(:,2) & ...
dyUpperBound > mtx_pointList(:,2), : );
</code></pre>
<p>However, I suspect that this is slowing my code down considerably.</p>
<p>What is a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:01:03.200",
"Id": "81625",
"Score": "1",
"body": "The keyword you are looking for is quadtree."
}
] |
[
{
"body": "<p>if you only need to select once then there is no need to sort at all; filtering can happen in \\$ O \\left( n \\right) \\$ while the sort needs \\$ O \\left( n \\log n \\right) \\$</p>\n\n<p>if you need to select multiple times then put them in a \\$ n \\times n \\$ grid structure, where each grid is a list of points that lie within it</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:53:49.883",
"Id": "81621",
"Score": "1",
"body": "MathJax was introduced to Code Review [yesterday](http://meta.codereview.stackexchange.com/a/1708/27623)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:27:35.127",
"Id": "39418",
"ParentId": "39409",
"Score": "2"
}
},
{
"body": "<p>Prefiltering all relevant x-values with a binary search could speed up the process.</p>\n\n<pre><code>[a,A]=myFind2(mtx_region(:,1),dxLowerBound,dxUpperBound);\n\nxpoints=mtx_region(a:A,:);\nmtx_region = xpoints( dyLowerBound < xpoints(:,2) & ...\n dyUpperBound > xpoints(:,2), : );\n</code></pre>\n\n<p>Binary search on sorted arrays is already discussed <a href=\"https://stackoverflow.com/questions/20166847/faster-version-of-find-for-sorted-vectors-matlab/20167257#20167257\">here</a>.</p>\n\n<pre><code>function [b,c]=myFind2(x,A,B)\na=1;\nb=numel(x);\nc=1;\nd=numel(x);\nwhile (a+1<b||c+1<d)\n lw=(floor((a+b)/2));\n if (x(lw)<A)\n a=lw;\n else\n b=lw;\n end\n lw=(floor((c+d)/2));\n if (x(lw)<=B)\n c=lw;\n else\n d=lw;\n end\nend\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T02:52:44.893",
"Id": "40075",
"ParentId": "39409",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40075",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:12:20.057",
"Id": "39409",
"Score": "4",
"Tags": [
"performance",
"matlab"
],
"Title": "What's the fastest way to get the points I want out of a huge blob?"
}
|
39409
|
<p>Being curious to see which tags on this site get the most attention, I developed a <a href="http://data.stackexchange.com/codereview/revision/160176/204146" rel="nofollow">Stack Exchange Data Explorer query</a>:</p>
<pre><code>WITH CanonicalTags AS (
SELECT Id, TagName, Id AS AliasId, TagName AS Alias
FROM Tags
WHERE NOT EXISTS (
SELECT Id
FROM TagSynonyms
WHERE SourceTagName=TagName AND ApprovedByUserId IS NOT NULL
)
UNION
SELECT Tags.Id, Tags.TagName, Alias.Id AS AliasId, Alias.TagName
FROM Tags
INNER JOIN TagSynonyms
ON TargetTagName=TagName
INNER JOIN Tags AS Alias
ON Alias.TagName=SourceTagName
WHERE ApprovedByUserId IS NOT NULL
), TagQuestionStats AS (
SELECT Tags.Id AS Id
, Tags.TagName AS TagName
, AVG(CAST(Questions.Score AS DECIMAL)) AS AvgScore
, STDEV(Questions.Score) AS StdDevScore
, COUNT(Questions.Id) AS N
FROM CanonicalTags AS Tags
INNER JOIN PostTags
ON PostTags.TagId=Tags.AliasId
INNER JOIN Posts AS Questions
ON Questions.Id=PostTags.PostId
GROUP BY Tags.Id, Tags.TagName
), TagAnswerStats AS (
SELECT Tags.Id AS Id
, Tags.TagName AS TagName
, AVG(CAST(Answers.Score AS DECIMAL)) AS AvgScore
, STDEV(Answers.Score) AS StdDevScore
, COUNT(Answers.Id) AS N
FROM CanonicalTags AS Tags
INNER JOIN PostTags
ON PostTags.TagId=Tags.AliasId
INNER JOIN Posts AS Questions
ON Questions.Id=PostTags.PostId
INNER JOIN Posts AS Answers
ON Answers.ParentId=Questions.Id
WHERE
Answers.PostTypeId=2
GROUP BY Tags.Id, Tags.TagName
)
SELECT '<' + QStats.TagName + '>' AS [TagName]
, ROUND(QStats.AvgScore, 2) AS [Avg Qst Score]
, ROUND(QStats.StdDevScore, 2) AS [Qst Score Std Dev]
, QStats.N AS [# Qst]
, ROUND(AStats.AvgScore, 2) AS [Avg Ans Score]
, ROUND(AStats.StdDevScore, 2) AS [Ans Score Std Dev]
, AStats.N AS [# Ans]
, ROUND(CAST(AStats.N AS DECIMAL) / CAST(QStats.N AS DECIMAL), 2) AS [Avg # Ans/Qst]
FROM
TagQuestionStats AS QStats
LEFT OUTER JOIN TagAnswerStats AS AStats
ON AStats.Id=QStats.Id
ORDER BY 5 DESC, 2 DESC, 7, 4, 1;
</code></pre>
<p>I'd like to ask:</p>
<ol>
<li>Some of the numbers don't round to two decimal places very well. Is that due to a bug in SQL Server, or am I using inappropriate rounding techniques? (The exact numbers don't matter; I'd much rather have a compact presentation.)</li>
<li>Is there an easier way to canonicalize the tags?</li>
<li>Any comments about my SQL formulation in general?</li>
<li>Any suggestions for making the query itself more meaningful?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:23:40.503",
"Id": "65987",
"Score": "1",
"body": "I know, I'm blurring the lines with http://meta.codereview.stackexchange.com/ a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:33:20.140",
"Id": "65990",
"Score": "6",
"body": "this is a valid code review to me"
}
] |
[
{
"body": "<ol>\n<li>I think that the rounding behaviour is a bug. The output looks just fine if you tick the \"Text-only results\" checkbox.</li>\n<li><p><a href=\"http://data.stackexchange.com/code%20review%20stack%20exchange/revision/160176/204311\" rel=\"nofollow\">Simplified tag\ncanonicalization</a>:</p>\n\n<pre><code>WITH CanonicalTags AS (\n SELECT Master.Id AS Id\n , Master.TagName AS TagName\n , Synonym.Id AS AliasId\n , Synonym.TagName AS AliasName\n FROM Tags AS Synonym\n LEFT OUTER JOIN TagSynonyms\n ON SourceTagName=Synonym.TagName AND ApprovedByUserId IS NOT NULL\n LEFT OUTER JOIN Tags AS Master\n ON Master.TagName=COALESCE(TargetTagName, Synonym.TagName)\n)\n…\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T01:12:30.473",
"Id": "39433",
"ParentId": "39410",
"Score": "3"
}
},
{
"body": "<p>Your code is, for the most part, consistently styled, and predictably structured, which is nice. I am not a fan of the comma-on-the-new-line style of continuation. I prefer the comma at the end. But, at least you are consistent with this.</p>\n\n<p>One inconsistency which I see is that for smaller selects you have multiple selected columns on a single line.</p>\n\n<pre><code>SELECT Tags.Id, Tags.TagName, Alias.Id AS AliasId, Alias.TagName\n ....\n</code></pre>\n\n<p>To be consistent with the other selects, as much as these are short statements, you should maintain consistency:</p>\n\n<pre><code>SELECT Tags.Id\n , Tags.TagName\n , Alias.Id AS AliasId\n , Alias.TagName\n ....\n</code></pre>\n\n<p>There is only one example of it in your code, but I really dislike multiple conditions on a single line:</p>\n\n<pre><code>WHERE SourceTagName=TagName AND ApprovedByUserId IS NOT NULL\n</code></pre>\n\n<p>This really should be:</p>\n\n<pre><code>WHERE SourceTagName=TagName\n AND ApprovedByUserId IS NOT NULL\n</code></pre>\n\n<p>The UNION condition is also very buried in there, and it has too much indentation ;-)</p>\n\n<p>Finally, white-space is cheap in SQL, I really don't like the space-less <code>arg=val</code> expressions, spacing them is easy <code>arg = val</code>.</p>\n\n<p>Right, that's the nit-picky stuff done.</p>\n\n<p>Talking about the UNION, the statement could be rewritten as:</p>\n\n<pre><code>SELECT IsNull(Main.TagName, Alias.TagName) AS TagName\n , IsNull(Main.Id, Alias.Id ) AS Id\n , Alias.Id AS AliasId\n FROM Tags AS Alias\n LEFT JOIN TagSynonyms \n ON SourceTagName = Alias.TagName\n LEFT JOIN Tags AS Main\n ON TargetTagName = Main.TagName\n</code></pre>\n\n<p>I prefer the more compact result, although it is debatable as to whether the \"Outer\" Join is a better solution than the UNION. Outer joins can lead to confusion. So can UNIONS and I prefer the outer join.</p>\n\n<p>In the above query I have removed the <code>Alias</code> TagName since it is not used outside the sub-select.</p>\n\n<p>I also found the final 'assimilation' of all the data in the final select to have too many casts and data conversions. The actual logic was lost in the detail. I moved the complicating CASTS to the previous <code>with</code> clauses.</p>\n\n<p>Finally, the indexed <code>ORDER BY</code> has caught a number of people out in the past, as it is too easy to change columns and suddenly the data ordering is off, even though the query still runs. I always recommend named-column ordering.</p>\n\n<p>Putting this all together, I have the SQL:</p>\n\n<pre><code>WITH CanonicalTags AS (\n SELECT IsNull(Main.TagName, Alias.TagName) AS TagName\n , IsNull(Main.Id, Alias.Id ) AS Id\n-- , Alias.TagName AS AliasName\n , Alias.Id AS AliasId\n FROM Tags AS Alias\n LEFT JOIN TagSynonyms \n ON SourceTagName = Alias.TagName\n LEFT JOIN Tags AS Main\n ON TargetTagName = Main.TagName\n), TagQuestionStats AS (\n SELECT Tags.Id AS Id\n , Tags.TagName AS TagName\n , CAST(AVG(CAST(Questions.Score AS DECIMAL)) AS DECIMAL(8,2)) AS AvgScore\n , CAST(STDEV(Questions.Score) AS DECIMAL(8,2)) AS StdDevScore\n , CAST(COUNT(Questions.Id) AS DECIMAL(8,2)) AS N\n FROM CanonicalTags AS Tags\n INNER JOIN PostTags\n ON PostTags.TagId=Tags.AliasId\n INNER JOIN Posts AS Questions\n ON Questions.Id=PostTags.PostId\n GROUP BY Tags.Id, Tags.TagName\n), TagAnswerStats AS (\n SELECT Tags.Id AS Id\n , Tags.TagName AS TagName\n , CAST(AVG(CAST(Answers.Score AS DECIMAL)) AS DECIMAL(8,2)) AS AvgScore\n , CAST(STDEV(Answers.Score) AS DECIMAL(8,2)) AS StdDevScore\n , CAST(COUNT(Answers.Id) AS DECIMAL(8,2)) AS N\n FROM CanonicalTags AS Tags\n INNER JOIN PostTags\n ON PostTags.TagId=Tags.AliasId\n INNER JOIN Posts AS Questions\n ON Questions.Id=PostTags.PostId\n INNER JOIN Posts AS Answers\n ON Answers.ParentId=Questions.Id\n WHERE\n Answers.PostTypeId=2\n GROUP BY Tags.Id, Tags.TagName\n)\nSELECT '<' + QStats.TagName + '>' AS [TagName]\n , QStats.AvgScore AS [Avg Qst Score]\n , QStats.StdDevScore AS [Qst Score Std Dev]\n , QStats.N AS [# Qst]\n , AStats.AvgScore AS [Avg Ans Score]\n , AStats.StdDevScore AS [Ans Score Std Dev]\n , AStats.N AS [# Ans]\n , ROUND(AStats.N / QStats.N, 2) AS [Avg # Ans/Qst]\n FROM\n TagQuestionStats AS QStats\n LEFT OUTER JOIN TagAnswerStats AS AStats\n ON AStats.Id=QStats.Id\n ORDER BY [Avg Ans Score] DESC\n , [Avg Qst Score] DESC\n , [# Ans]\n , [# Qst]\n , [TagName];\n</code></pre>\n\n<p>This query supports this <a href=\"http://data.stackexchange.com/code%20review%20stack%20exchange/query/160348/average-score-for-questions-and-answers-by-tag\" rel=\"nofollow\">fork of your original question</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T01:49:07.470",
"Id": "66031",
"Score": "0",
"body": "`CAST(number AS DECIMAL(8,2))` seems to work around the `ROUND(number, 2)` formatting bug in SEDE as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T17:35:32.887",
"Id": "67379",
"Score": "0",
"body": "Thanks! Incorporated remarks [here](http://data.stackexchange.com/codereview/revision/160176/207988)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T01:41:43.110",
"Id": "39437",
"ParentId": "39410",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39437",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:22:03.747",
"Id": "39410",
"Score": "10",
"Tags": [
"sql",
"sql-server",
"floating-point",
"stackexchange"
],
"Title": "SE Data Explorer Query: Average score for questions and answers, by tag"
}
|
39410
|
<p>SEDE (<a href="https://data.stackexchange.com" rel="nofollow noreferrer">Stack Exchange Data Explorer</a>) now includes all public beta sites, and allows querying a recent snapshot of the sites' data, including questions, answers, comments, users, etc.</p>
<p>This tool can be used to fetch data that can help assess beta status and come up with action plans. See <a href="https://codereview.meta.stackexchange.com/questions/1429/sede-is-up-what-now-wonderland">Stack Exchange Data Explorer is up. What now, Wonderland?</a> on CR.Meta.</p>
<p>Questions about Data Explorer queries should also be tagged with <a href="/questions/tagged/sql" class="post-tag" title="show questions tagged 'sql'" rel="tag">sql</a> and <a href="/questions/tagged/sql-server" class="post-tag" title="show questions tagged 'sql-server'" rel="tag">sql-server</a>.</p>
<p>For general information about the Stack Exchange API, see <a href="https://stackapps.com">https://stackapps.com</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-16T20:22:41.110",
"Id": "39411",
"Score": "0",
"Tags": null,
"Title": null
}
|
39411
|
Questions about Stack Exchange APIs, Stack Exchange Data Explorer (SEDE), or any hacks to work with Stack Exchange sites.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:22:41.110",
"Id": "39412",
"Score": "0",
"Tags": null,
"Title": null
}
|
39412
|
<p>For many programming languages, a namespace is a context for their identifiers. In a filesystem, an example of a namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory, but one file may have the same name multiple times.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-16T20:52:13.490",
"Id": "39416",
"Score": "0",
"Tags": null,
"Title": null
}
|
39416
|
For many programming languages, namespace is a context for their identifiers. Use this tag to indicate concerns about appropriate usage of namespaces.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:52:13.490",
"Id": "39417",
"Score": "0",
"Tags": null,
"Title": null
}
|
39417
|
<p>This was our old site that I am redesigning.</p>
<p><img src="https://i.stack.imgur.com/mjEYm.png" alt="old"></p>
<p>Someone else hardcoded with inline CSS and javascript in tables. </p>
<p>I wanted to make it dynamic, so I added Mustache and made this template:</p>
<pre><code>{{#labs}}
<div class="lab">
<h4>{{{lab}}}</h4>
<p>
{{#stadt}}
<span><i class="fa fa-building-o"></i></span><span>{{{stadt}}}</span>
<br />
{{/stadt}}
{{#telefon}}
<span><i class="fa fa-phone"></i></span><span>{{{telefon}}}</span>
<br />
{{/telefon}}
{{#webseite}}
<span><i class="fa fa-desktop"></i></span>
<span>
<a href="http://{{{webseite}}}" target="_blank">{{{webseite}}}</a>
</span>
{{/webseite}}
</p>
</div>
{{/labs}}
</code></pre>
<p>Here is some of the JSON file:</p>
<pre><code>{ "labs" : [
{
"lab":"Ri&szlig;mann Zahntechnik GmbH",
"stadt":"D-06917 Jessen",
"telefon":"+49 (0) 3537 21 38 61",
"webseite":"www.rissmann-zahntechnik.de"
},
</code></pre>
<p>Would it make a big enough difference to not have the full word as the name? So maybe like <code>"l"</code> instead of <code>"lab"</code> and <code>"w"</code> instead of <code>"webseite"</code>, etc.</p>
<p>Here is the result of the listings:</p>
<p><img src="https://i.stack.imgur.com/ES6Ze.png" alt="current"></p>
<p>The even spacing between the icon and the values was achieved by this CSS rule:</p>
<pre><code>.lab i { width: 27px; }
</code></pre>
<p>Also, does it make sense to have it in a single <code><p></code> tag, or should I consider placing each value in its own <code><div></code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:48:26.150",
"Id": "66026",
"Score": "2",
"body": "We're talking about a total savings of `66 + (19*labs)` characters at the expense of intuitive reading. I would argue that it's not worth it as it will have virtually no (maybe saving 100 bytes if you're not gzipping your content...) impact on your user or your server"
}
] |
[
{
"body": "<p>By using excessive markup for presentational purposes, the template is the exact opposite of clean.</p>\n\n<pre><code><span><i class=\"fa fa-phone\"></i></span><span>{{{telefon}}}</span><br />\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code><span class=\"fa fa-phone\">{{{telefon}}}</span>\n<!-- span set to `display: block` with a `:before` pseudo element to contain the icon -->\n</code></pre>\n\n<p>If you're not able to do this because of a library you're depending on, my recommendation is to find a better library.</p>\n\n<p>By moving away from tables, you've committed a sin that's just as bad as using tables for layout: you're using non-tabular markup for tabular data. It is understandable that you don't want it to <em>look</em> like a table (either for aesthetic or responsive reasons), but tables don't have to look like tables any more than a list has to look like a list.</p>\n\n<p>Go back to using tables and make adjustments to your CSS instead:</p>\n\n<p><a href=\"http://jsfiddle.net/SGK8Q/\" rel=\"nofollow\">http://jsfiddle.net/SGK8Q/</a></p>\n\n<p>What the markup should end up looking similar to this:</p>\n\n<pre><code><table>\n <thead>\n <tr>\n <th>Lab</th>\n <th>Contact</th>\n <th>Phone</th>\n <th>Website</th>\n </tr>\n </thead>\n\n <tbody>\n <tr>\n <td class=\"name\">ABC</td>\n <td class=\"contact\">Johnny</td>\n <td class=\"phone\">555-1234</td>\n <td class=\"url\">http://abc.example.com/</td>\n </tr>\n\n <tr>\n <td class=\"name\">DEF</td>\n <td class=\"contact\">Billy</td>\n <td class=\"phone\">555-1234</td>\n <td class=\"url\">http://def.example.com/</td>\n </tr>\n\n <tr>\n <td class=\"name\">GHI</td>\n <td class=\"contact\">Dave</td>\n <td class=\"phone\">555-1234</td>\n <td class=\"url\">http://abc.example.com/</td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p>The CSS:</p>\n\n<pre><code>table, tbody, tr, td, th {\n display: block;\n}\n\nthead {\n display: none;\n}\n\n/* everything past here is optional */\ntr + tr {\n margin-top: 1em;\n}\n\n.name {\n font-size: 1.2em;\n font-weight: bold;\n}\n\n.url {\n color: blue;\n text-decoration: underline;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:24:31.750",
"Id": "66198",
"Score": "0",
"body": "The `<span class=\"fa fa-phone\">{{{telefon}}}</span>` would not work because the `class=\"fa fa-phone\"` is for [font awesome icons](http://fontawesome.io/icons/). By \"will not work\" I mean that yes, the icon will display next to the phone number, but it then interferes with inherited styles for the text and loses the desired spacing between the icon. And thanks for pointing out how tables would be more appropriate."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:30:09.213",
"Id": "39486",
"ParentId": "39425",
"Score": "3"
}
},
{
"body": "<p>As megawac said, do not give up readability for a few bytes.</p>\n\n<p>Your template looks heavy because you deal with missing data thru {{#xx}} and because those icons take up space. I am not a big fan of logic in templates, but in this particular case you made the right call.</p>\n\n<p>I think one paragraph tag is better than many, so I would keep it that way.</p>\n\n<p>Still, I wonder if you can replace <code><span><i class=\"fa fa-building-o\"></i></span></code> with <code><i class=\"fa fa-building-o\"></i></code>, I can't tell why you need the extra enclosing span.</p>\n\n<p>Finally, I think you should indent your <code>stadt</code> and <code>telelephon</code> blocks over a few lines like you did for<code>#webseite</code>, it becomes more readable for me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T15:03:50.427",
"Id": "39657",
"ParentId": "39425",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:22:21.790",
"Id": "39425",
"Score": "4",
"Tags": [
"javascript",
"css",
"json",
"template",
"mustache"
],
"Title": "How clean is this mustache template for a listing page?"
}
|
39425
|
<p>Preface: I'm starting to learn C# and I don't want to port any of my bad habits from other languages, so I'm following convention wherever possible.</p>
<p>Using the default Visual Studio code formatting, this relatively simple function requires 14 lines of code.</p>
<pre><code>public void add(int[] values, Func<int, int> transform = null)
{
foreach (int v in values)
{
if (transform == null)
{
add(v);
}
else
{
add(transform(v));
}
}
}
</code></pre>
<p>My first thought was to use the <code>??</code> operator to do something like the following snippet, but apparently that's gibberish.</p>
<pre><code>public void add(int[] values, Func<int, int> transform = null)
{
foreach (int v in values)
{
add(transform(v) ?? v);
}
}
</code></pre>
<p>Is there a more concise and/or readable way to write the following method?</p>
|
[] |
[
{
"body": "<p>There are at least two answers.\nThe short one:</p>\n\n<pre><code>public void add(int[] values, Func<int, int> transform = null)\n{\n foreach (int v in values)\n add( (transform != null) ? transform(v) : v);\n}\n</code></pre>\n\n<p>The efficient one:</p>\n\n<pre><code>public void add(int[] values, Func<int, int> transform = null)\n{\n if( transform != null) \n foreach (int v in values)\n add( transform(v));\n else\n foreach (int v in values)\n add( v);\n}\n</code></pre>\n\n<p>Not nice, but you wanted a short version.</p>\n\n<p>Maybe someone has a LINQ at hand which does this even better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:09:42.870",
"Id": "66013",
"Score": "0",
"body": "Your first block of code is what I'm looking for. Also, your 'efficient' block may not be so efficient. I'm believe the JIT would use branch prediction to optimize your first approach. http://msdn.microsoft.com/en-us/magazine/dd569747.aspx#id0400010"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T08:42:25.290",
"Id": "66064",
"Score": "0",
"body": "The second snippet sounds very much like a premature optimization to me. A null check is very cheap, there is no reason to make your code twice as long just for that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:26:57.830",
"Id": "39428",
"ParentId": "39427",
"Score": "3"
}
},
{
"body": "<p>It may not be more concise, but it is definitely more readable.</p>\n\n<pre><code>public void addMany(int[] values)\n{\n foreach (int v in values)\n {\n add(v);\n }\n }\n\npublic void addTransformMany(int[] values, Func<int,int> transform)\n{\n foreach (int v in values)\n {\n add(transform(v));\n }\n }\n</code></pre>\n\n<p>Maybe not what you are looking for, but I think having two methods that are explicit about what they do is much more <em>readable</em> than a single method with an execution branch that depends on an optional parameter. The method signature should make it clear what it does, without requiring the reader to inspect the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:22:35.403",
"Id": "66014",
"Score": "0",
"body": "Thanks for the response, however, I don't really agree in this specific case. It seems pretty logical to me, that, if you pass in a transform function, it will be used while adding the values. In general, I do agree with the idea, especially when the branches are unrelated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T05:12:10.327",
"Id": "66047",
"Score": "0",
"body": "@LawrenceBarsanti I suppose my answer is somewhat subjective. I have found that optional parameters (with default values) can cause headaches in C# code in the long run. I think it is similar to having multiple public constructors for a class, rather than factory methods that describe the intent of the constructor definitions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:51:14.267",
"Id": "39429",
"ParentId": "39427",
"Score": "2"
}
},
{
"body": "<p>Your original use of the null coalescing operator didn't work because it was testing the output of calling the method <code>transform(v)</code> and not testing whether transform is null. </p>\n\n<p>If transform was null, the operation would throw an exception.</p>\n\n<p>@JensG use of the conditional operator is the most concise.</p>\n\n<p>Another option is to declare a NullTransform</p>\n\n<pre><code>Func<int,int> NullTransform = x=>x;\n</code></pre>\n\n<p>And use this when transform is not set.</p>\n\n<pre><code>public void add(int[] values, Func<int, int> transform = null)\n{\n transform = transform ?? NullTransform; // Optionally test and set here.\n foreach (int v in values)\n add(transform(v));\n}\n</code></pre>\n\n<p>Sadly, you cannot set the default in the method call to the NullTransform instance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:35:17.363",
"Id": "66095",
"Score": "0",
"body": "The code is from a simple Accumulator object. The other add() method adds a single value to the accumulator, while, the one in my question adds an array of values to to the accumulator."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T02:11:56.357",
"Id": "39438",
"ParentId": "39427",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39428",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:11:34.457",
"Id": "39427",
"Score": "3",
"Tags": [
"c#",
"beginner"
],
"Title": "Is there a more concise and/or readable way to write the following method?"
}
|
39427
|
<p>I have the following code to log changes using Entity Framework 6.</p>
<p>At the moment it only logs changes to a particular table - but I intend to expand it to cope with any table. I'm not sure of the best way to extract the table name.</p>
<p>I call this code before <code>Db.SaveChanges</code>. Db is the DBContext.</p>
<pre><code>private void LogHistory()
{
var entries = this.Db.ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted)
.ToList();
foreach (var entry in entries)
{
foreach (string o in entry.CurrentValues.PropertyNames)
{
var property = entry.Property(o);
var currentVal = property.CurrentValue == null ? "" : property.CurrentValue.ToString();
var originalVal = property.OriginalValue == null ? "" : property.OriginalValue.ToString();
if (currentVal != originalVal)
{
if (entry.Entity.GetType().Name.Contains("PropetyPair"))
{
// make and add log record
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:56:13.507",
"Id": "66017",
"Score": "0",
"body": "I'm not an entity framework guru but I would have thought you might inherit the context and override `SaveChanges()` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:53:53.557",
"Id": "66028",
"Score": "0",
"body": "Yes I actually do that, but i left it out for simplicity, since I don't think it is relevant to my question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T16:39:06.560",
"Id": "82989",
"Score": "0",
"body": "You may find FrameLog useful. It is a general purpose EF logging library. Either as an alternative to writing this yourself or as a source of code to compare with (it is open source)."
}
] |
[
{
"body": "<p>Not a big deal, but this:</p>\n\n<blockquote>\n<pre><code>var currentVal = property.CurrentValue == null ? \"\" : property.CurrentValue.ToString();\nvar originalVal = property.OriginalValue == null ? \"\" : property.OriginalValue.ToString();\n</code></pre>\n</blockquote>\n\n<p>Can be shortened to this:</p>\n\n<pre><code>var currentVal = (property.CurrentValue ?? string.Empty).ToString();\nvar originalVal = (property.OriginalValue ?? string.Empty).ToString();\n</code></pre>\n\n<blockquote>\n <p><em>I'm not sure of the best way to extract the table name.</em></p>\n</blockquote>\n\n<p>You're not doing that. You're looking at the <em>name of the type of the entity</em> - being an object/relational <em>mapper</em>, EF maps that <em>entity</em> to a <em>table</em>; if you need the <em>table name</em> then you need to look at the entity's table mappings.</p>\n\n<blockquote>\n <p><em>I intend to expand it to cope with any table</em></p>\n</blockquote>\n\n<p>How about having an <code>IEnumerable<Type></code> where you have all the entity types you want to log changes for, and then instead of getting the type's name and comparing with some magic string, you can just do <code>_monitoredTypes.Contains(typeof(entry.Entity))</code> (not tested, just a thought).</p>\n\n<p>In terms of <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a>, you're looping too much:</p>\n\n<pre><code>if (entry.Entity.GetType().Name.Contains(\"PropetyPair\"))\n</code></pre>\n\n<p>This condition doesn't need <code>string o</code>, as it's working off <code>entry</code> - thus, you can move that condition up two levels and only enter the 2nd loop when the entity type is interesting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T04:39:16.070",
"Id": "39858",
"ParentId": "39430",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "39858",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:47:07.353",
"Id": "39430",
"Score": "10",
"Tags": [
"c#",
"performance",
"entity-framework"
],
"Title": "Logging Entity Framework Changes - improve performance"
}
|
39430
|
<p><a href="http://esolangs.org/wiki/Fishstacks">Fishstacks</a> is a <a href="http://esolangs.org/wiki/Deadfish">deadfish</a> derivative based on a stack the stack can only hold four elements when a fifth element is pushed the bottom element is kicked out and eventually printed out to the screen.</p>
<p>I've come up with an interpreter in TI-BASIC for my calculator. However, I fell slightly guilty about using all four variables <code>ABCD</code>. I wonder if there could be a better way? Maybe with lists (arrays). I've just started learning about them, so I don't feel confident switching over yet. Any guidance would be appreciated.</p>
<p>Also, in order not to push anything to the screen until something falls off the stack, I've had to initialize variables to <code>-2</code>. This is the main reason I have not converted to arrays yet; I don't see how they could address this issue. (maybe even throw a <code>DOMAIN</code> error).</p>
<pre><code>:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:0->I
:-2->A
:A->B
:B->C
:C->D
:Input Str1
:While I<length(Str1)
:I+1->I
:sub(Str1,I,1)->Str2
:If Str2="I"
:A+1->A
:If Str2="D"
:A-1->A
:If Str2="S"
:A^2->A
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:B->C
:A->B
:0->A
:End
:If A=256 or A=-1
:0->A
:If A=-2
:Stop
:End
</code></pre>
<p>By convention, I've represented the <code>STO→</code> character, <code>→</code> with <code>-></code></p>
|
[] |
[
{
"body": "<p>Beyond the bad names that you are already aware of, I see a few things that could be improved.</p>\n\n<p><code>str1</code> and <code>str2</code> are bad variable names as well. They should be <code>str</code> and <code>chr</code> respectively. Those names would properly represent the data and make this code much more understandable. It would be instantly clear to anyone looking at the code that you're looping through each character of the string the user inputs.</p>\n\n<p>This section of code makes no sense.</p>\n\n<blockquote>\n<pre><code>:If Str2=\"P\" and D>-1\n:Then\n:Disp D\n:C->D\n:B->C\n:A->C\n:0->A\n:End\n</code></pre>\n</blockquote>\n\n<p>Translated into a \"normal\" basic language, it looks like this.</p>\n\n<pre><code> If char = \"P\" And d > -1 Then\n Print d\n\n d = c\n c = b\n c = a\n a = 0\n End If\n</code></pre>\n\n<p>And it is instantly obvious that you only need to make the assignment to <code>c</code> once.</p>\n\n<pre><code>:If Str2=\"P\" and D>-1\n:Then\n:Disp D\n:C->D\n:A->C\n:0->A\n:End\n</code></pre>\n\n<p>The other improvement I can see here, is that I think it makes a lot of sense to use a <a href=\"http://www.ticalc.org/programming/columns/83plus-bas/cherny/#for\">For Loop</a> instead of a While loop here. That way you wouldn't have to increment <code>I</code> manually on every iteration of the loop. It would make this little program a little cleaner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:34:55.070",
"Id": "134230",
"Score": "3",
"body": "Unfortunately it seems like you are not familiar with the language; other than catching the typo, there's really no improvements. Strings cannot be renamed, For( loops take more space, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:36:53.663",
"Id": "134231",
"Score": "0",
"body": "I'm not very familiar @Timtech. I was working from the documentation, but even if a For loop takes more space, I still feel it would be a better option as you wouldn't have to manually increment the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:38:11.437",
"Id": "134232",
"Score": "1",
"body": "http://tibasicdev.wikidot.com/for"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:41:53.073",
"Id": "134236",
"Score": "0",
"body": "Yes. I read that earlier when writing the review. You're under no obligation to take my advice @Timtech, but I stand by my advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:45:13.577",
"Id": "134237",
"Score": "0",
"body": "Okay then, sorry for the harshness initially... I've asked some other friends to try to optimize it, hopefully I can get some better input..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:46:35.033",
"Id": "134238",
"Score": "1",
"body": "I ope so too! And the bounty is open for another week, so maybe someone here will take notice. =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:48:19.170",
"Id": "134239",
"Score": "4",
"body": "Yep, one of my friends says he's writing up one now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T11:24:12.800",
"Id": "134335",
"Score": "0",
"body": "TI calculators have RAM on the order of kilobytes. Short variable names are the norm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T11:45:32.273",
"Id": "134339",
"Score": "0",
"body": "@200_success I did some quick research and updated my answer. Does that look better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-19T00:29:39.693",
"Id": "134760",
"Score": "2",
"body": "Well, the remark about string names is still pointless: you can't name variables in TI-BASIC. There are like a dozen of string variables named `Str1`, `Str2`, `Str3`... and you can't do anything about it. You have to use these cryptic names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-06T00:04:08.317",
"Id": "144435",
"Score": "0",
"body": "@200_success TI-Basic is a tokenized language, which means that there are only a certain amount of variables, and they are already a certain size (1 or 2 bytes) when referenced in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-02T00:54:01.573",
"Id": "360467",
"Score": "0",
"body": "@Morwenn, there are `Str1` to `Str9` plus `Str0`, so 10 (if you want to be exact)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T16:15:44.637",
"Id": "73840",
"ParentId": "39431",
"Score": "15"
}
},
{
"body": "<p>I was asked by @Timtech to join + post an improvement. Using arrays is a lot easier to understand, and there were so many optimizations that I decided to completely re-write the code. I'm sure it could be improved by other advanced programmers like me, as I'm using several long expressions here... note that <code>L1</code> represents list #1 (<code>2nd</code> + <code>1</code> on the calculator) and <code>~</code> is the negative token.</p>\n\n<pre><code>:ClrHome\n:Disp \"FISHSTACKS IDSP\",\"INTERPRETER\n:DelVar IInput Str1\n:DelVar L1~{2,2,2,2→L1\n:While I<length(Str1\n:I+1→I\n:sub(Str1,I,1→Str2\n:(Str2=\"I\")-(Str2=\"D\n:Ans+L1(4→L1(4\n:If Str2=\"S\n:L1(4)²→L1(4\n:If Str2=\"P\n:Then\n:L1(1\n:If 2+Ans\n:Disp Ans\n:ΔList(cumSum(L1->L1\n:0->L1(4\n:End\n:L1(4\n:If Ans=256 or Ans<0\n:0->L1(4\n:End\n</code></pre>\n\n<p><strong>Improvements</strong></p>\n\n<ol>\n<li>Saved bytes by removing several unneeded ending parentheses and quotes</li>\n<li>Used <code>DelVar</code> since it does not need a following colon</li>\n<li>Used an array instead of four variables</li>\n<li>Used a complex expression <code>:(Str2=\"I\")-(Str2=\"D</code> saved to <code>Ans</code> to save space</li>\n<li>Used <code>ΔList(cumSum(L1->L1</code> to get <code>L1</code> minus its first element</li>\n<li>Several others I'm not listing due to their minisculity; mainly using <code>Ans</code> to save space and speed</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T20:05:47.393",
"Id": "134244",
"Score": "0",
"body": "Wow great, I'm glad you could make it! Enjoy your stay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T20:07:05.083",
"Id": "134245",
"Score": "2",
"body": "Thanks @Timtech, I'll probably be answering your other questions in the near future, whenever I have the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T02:09:55.683",
"Id": "134275",
"Score": "5",
"body": "Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-19T00:26:03.433",
"Id": "134758",
"Score": "4",
"body": "Haha, that good old TI-BASIC where not closing the parenthesis and the strings is the norm :D"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T20:04:49.110",
"Id": "73858",
"ParentId": "39431",
"Score": "18"
}
},
{
"body": "<pre><code>:ClrHome\n:Disp \"FISHSTACKS IDSP\",\"INTERPRETER\"\n:-{2,2,2,0->L1\n:Input Str1\n:For(I,1,length(Str1\n:sub(Str1,I,1\n:If Ans≠\"P\"\n:Then\n:(Ans=\"I\")-(Ans=\"D\")+L1(4)^int(e^(Ans=\"S\"->L1(4\n:If Ans≥0 and Ans≠256\n:Else\n:L1(1\n:If 2+Ans\n:Disp Ans\n:augment(ΔList(cumSum(L1)),{0->L1\n:End\n:End\n</code></pre>\n\n<p>I was able to shorten FlyAwayBirdie's answer even more by combining some expressions, moving the overflow checking earlier to take advantage of Ans, setting L1 in fewer bytes, using a For loop, and a couple of other things. Additionally, I initialized variables to -1 instead of -2, except for the initial accumulator which starts at 0 as per the spec.</p>\n\n<p>You can remove the close quotes at the ends of the lines.</p>\n\n<p>Edit: Saved a couple more bytes by not saving the substring to Str2.</p>\n\n<p>Edit: Fixed overflow functionality; however, undefined commands will now be recognized as \"P\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-25T01:07:07.260",
"Id": "166360",
"Score": "0",
"body": "Nice! Usually when he posts it's hard to improve upon it :P"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-24T15:00:32.027",
"Id": "91637",
"ParentId": "39431",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "73858",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:55:56.233",
"Id": "39431",
"Score": "23",
"Tags": [
"ti-basic",
"interpreter"
],
"Title": "TI-BASIC interpreter for Fishstacks"
}
|
39431
|
<p>I have an array that I want to enumerate using blocks concurrently. However, I'm having trouble making this thread safe. I am new to using blocks and locks, so I am hoping someone may be able to push me in the right direction for preventing this from crashing.</p>
<p>The point of this function is to loop over a number of files and folders.</p>
<ul>
<li>if folder, create a new dictionary item</li>
<li>if file, add as child to folder key</li>
<li>if folder, then recursively move into the folder to iterate over all files and folders and add to dictionary</li>
</ul>
<p>This builds a dictionary structure of the file system. However, it is slow and I would like to do this concurrently.</p>
<p>My main function looks like this:</p>
<pre><code>- (void)createDirectoryStructure:(NSString *)LR withArray:(NSMutableArray *)myArray {
__block NSFileManager *fm = [NSFileManager defaultManager];
__block BOOL isDir=NO;
__block NSString *local;
__block NSString *myKey;
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *url=obj;
if ([LR isEqualToString:@"L"]) {
myKey = [url stringByDeletingLastPathComponent];
local = [self.rootdirL.path stringByAppendingString:url];
[fm fileExistsAtPath:local isDirectory:&isDir];
if (!isDir)
[self updateStructureWithKey:myKey andURL:url isDir:isDir forLR:LR];
}
}];
}
</code></pre>
<p>This function calls <code>updateStructureWithKey</code> that looks like this:</p>
<pre><code>-(void) updateStructureWithKey:(NSString*)myKey andURL:(NSString*)url isDir:(BOOL)isDir forLR:(NSString*)LR
{
NSArray *components=[myKey pathComponents];
NSString *addPath=@"";
NSUInteger counter=0;
for (NSString *component in components){
NSString *createDir=[addPath stringByAppendingPathComponent:component];
addPath=createDir;
counter+=1;
if ((unsigned long)counter<(unsigned long)components.count){
NSString *addchild = [createDir stringByAppendingPathComponent:[components objectAtIndex:(unsigned long)counter]];
[self addDictionaryItem:createDir withURL:addchild withLR:LR isDir:TRUE];
}
}
[self addDictionaryItem:myKey withURL:url withLR:LR isDir:isDir];
}
</code></pre>
<p>Which again calls <code>addDictionaryItem</code>:</p>
<pre><code>-(void) addDictionaryItem:(NSString *) mykey withURL:(NSString *)myurl withLR:(NSString *)LR isDir:(BOOL) myIsDir
{
if ([self.dict objectForKey:mykey]) {
NSMutableArray *myarray = [[self.dict objectForKey:mykey] objectForKey:@"myarray"];
NSMutableArray *myarrayLR = [[self.dict objectForKey:mykey] objectForKey:@"LR"];
NSMutableArray *myarrayIsDir = [[self.dict objectForKey:mykey] objectForKey:@"isdir"];
NSMutableDictionary *attrDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:myarrayLR, @"LR",
myarray, @"myarray", myarrayIsDir, @"isdir",
nil];
if (![myarray containsObject:myurl]){
[myarray addObject:myurl];
[myarrayLR addObject:LR];
[myarrayIsDir addObject:[NSNumber numberWithBool:myIsDir]];
if ([theLock tryLock]) {
[self.dict setObject:attrDict forKey:mykey];
[theLock unlock];
}
}
else {
NSMutableArray *arrayOfFiles = [[NSMutableArray alloc] init];
[arrayOfFiles addObject:myurl];
NSMutableArray *arrayOfLR = [[NSMutableArray alloc] init];
[arrayOfLR addObject:LR];
NSMutableArray *arrayIsDir = [[NSMutableArray alloc] init];
[arrayIsDir addObject:[NSNumber numberWithBool:myIsDir]];
NSMutableDictionary *attrDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:arrayOfLR, @"LR",
arrayOfFiles, @"myarray", arrayIsDir, @"isdir",
nil];
if ([theLock tryLock]) {
[self.dict setObject:attrDict forKey:mykey];
[theLock unlock];
}
}
}
}
</code></pre>
<p>In the final function, I use an <code>NSLock</code> that is initialized as a property earlier. I thought that since the functions <code>updateStructureWithKey</code> and <code>addDictionaryItem</code> are defined inline of the block, I would not have to define their variables as <code>__block</code>, but since I am changing a property, I would have to use NSLock to make sure the change is thread safe.</p>
<p>Still, when I run this code, it crashes with "EXC_BAD_ACCESS (code=EXC_I386_GPFLT)", but the position where it crashes varies.</p>
<p>A simplified test version of this problem is available as a Xcode project on <a href="https://github.com/trondkr/testFiletree" rel="nofollow">GitHub</a>.</p>
<p>I appreciate suggestions and hints from anyone who can help me understand blocks and thread safety.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:39:41.700",
"Id": "74775",
"Score": "0",
"body": "Use Xcode Menu Product > Profile then Instruments with \"Time Profiler\" to see where most time is spent. And @synchronized is the easiest way to protect access to mutable objects."
}
] |
[
{
"body": "<ol>\n<li><p>The bottleneck of your code might not be where you think it is. I recommend reading the <a href=\"https://developer.apple.com/library/mac/documentation/Performance/Conceptual/PerformanceOverview/Introduction/Introduction.html#//apple_ref/doc/uid/TP40001410-CH202-SW1\" rel=\"nofollow\">Performance Guidelines</a> of Apple as well as the specific <a href=\"https://developer.apple.com/library/mac/documentation/Performance/Conceptual/FileSystem/FileSystem.html#//apple_ref/doc/uid/10000161i\" rel=\"nofollow\">File-System Performance Guidelines</a>. </p></li>\n<li><p>Typically the bottleneck is at accessing the drive. So in making your build-up of Dictionaries concurrent, you will not gain anything as there is only one drive. You are checking with NSFileManager on each item with <code>fileExistsAtPath</code> which might be the bottleneck. Try getting this information initially when building <code>myArray</code>. You're probably doing this also with Directory Enumerator. There are options to get specific metadata directly for an URL (like if it's a directory or folder) and this then will be cached in the <code>NSURL</code> (instead of working with path strings). </p></li>\n<li><p>Did you try to set some Breakpoints to find more details about <code>EXC_BAD_ACCESS</code>? Is it because of objects that were released too early? Or is it because of mutated while enumerating? Set a breakpoint on \"All Exceptions\" in Xcode and run the code with debugger. You will then be able to find more details on the crash. </p></li>\n<li><p>To isolate the crash, try to make the code in your block smaller. Remove all the code not really needed like this whole <code>LR</code> thing. </p></li>\n</ol>\n\n<p>I've analyzed the provided code which is not recursive. See <a href=\"https://github.com/mahal/testFiletree\" rel=\"nofollow\">my GitHub for the edits</a>. Here are my findings (for a test directory with 27’861 nested items):</p>\n\n<ul>\n<li><p>Most time was spent in the enumeration getting Filesystem metadata:</p>\n\n<blockquote>\n<pre><code> Time Self Symbol Name\n3568.0ms 53.6% -[SDAppDelegate createDirectoryStructure]\n2680.0ms 40.2% -[NSURLDirectoryEnumerator nextObject]\n</code></pre>\n</blockquote>\n\n<p>The new code only fetches as much metadata as needed and reuses it by using NSURL. </p></li>\n<li><p>The code for filling the array also did lots of duplicate checks: </p>\n\n<blockquote>\n<pre><code> Time Self Symbol Name\n2997.0ms 45.0% -[SDAppDelegate createArraysForLocalDirectories]\n2109.0ms 31.6% -[SDAppDelegate addDictionaryItem:withURL:isDir:]\n1121.0ms 16.8% -[NSArray containsObject:]\n</code></pre>\n</blockquote>\n\n<p>The new code does it a bit simpler. It could be even simpler, see comment in code. </p></li>\n<li><p>Another thing was Memory management. I removed the nested <code>autoreleasepool</code>, it's not really needed. See \"<a href=\"https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-SW2\" rel=\"nofollow\">Use Local Autorelease Pool Blocks to Reduce Peak Memory Footprint</a>\"</p></li>\n<li><p>As for concurrency, you were checking the mutable <code>self.dict</code> always if some key exists. If you want to write to this dict, you have to synchronize the access to it with a lock. The simplest one is <a href=\"https://developer.apple.com/library/mac/documentation/cocoa/conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW3\" rel=\"nofollow\">@synchronized()</a>.</p></li>\n<li><p>The improved code runs on the very same directory structure with the following times:</p>\n\n<blockquote>\n<pre><code> Time Self Symbol Name\n735.0ms 6.6% -[SDAppDelegate createDirectoryStructure]\n268.0ms 2.4% -[SDAppDelegate createArraysForLocalDirectories]\n</code></pre>\n</blockquote></li>\n<li><p>You could make a recursive code by using making a method that uses <code>NSDirectoryEnumerationSkipsSubdirectoryDescendants</code> and then call this method inside it again for directories. But that probably doesn't really speed it up. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:22:05.967",
"Id": "74651",
"Score": "0",
"body": "Thanks for your very useful comments and suggestions. I created a simplified version of my problem available on github. If you would take a look that would be greatly appreciated (https://github.com/trondkr/testFiletree). I have continued to work on this problem with no further success and could need some help. Thanks. T."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:40:06.800",
"Id": "42166",
"ParentId": "39435",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42166",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T01:32:47.347",
"Id": "39435",
"Score": "6",
"Tags": [
"array",
"objective-c",
"thread-safety",
"file-system",
"concurrency"
],
"Title": "Concurrently enumerating an array using blocks in a thread-safe way"
}
|
39435
|
<p>I am hoping to make this method run a little faster. I typically need to run this on a list with more than 100000 entries. Note that at the start and end of the list, I wish to weight the average so that it is closer to the start or end value, hence the smaller framesize.</p>
<pre><code>public PointPairList GetMovingAverage(int frameSize, PointPairList data)
{
PointPairList movAvgPoints = new PointPairList();
//Smooth each point in the list
for (int i = 0; i < data.Count; i++)
{
//get the window range
int actualFrameSize = frameSize;
int start = i - (frameSize/2);
int end = i + (frameSize/2);
//ensure the window is the same size at the source list boundaries
if (start < 0)
{
actualFrameSize = frameSize + start;
start = 0;
}
if (end >= data.Count)
{
actualFrameSize = frameSize + (data.Count - 1 - end);
}
//Now get the sum of the window
double sum = data.Skip(start).Take(actualFrameSize).Sum(p => p.Y);
//add the average point to the result
movAvgPoints.Add(new PointPair(data[i].X, sum/actualFrameSize));
}
return movAvgPoints;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T03:00:17.417",
"Id": "66040",
"Score": "1",
"body": "Just a note relating to your original post: *make your titles more descriptive to what your code does*. You can request what you would like specifically reviewed in your post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:16:27.087",
"Id": "66080",
"Score": "0",
"body": "How does your PointPairList look like? Does it implement IList<T>?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:32:30.387",
"Id": "66094",
"Score": "0",
"body": "@svick Yes it does"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-07T21:10:50.603",
"Id": "244998",
"Score": "0",
"body": "If a`PointPairList` constructor overload can take a `capacity` parameter, you can pre-allocate the size of the list, such like `List<T>` does and score a little performance gain by constructing it with `data.Count`."
}
] |
[
{
"body": "<p><code>Skip()</code> is not optimized for <code>IList<T></code>, it always enumerates the skipped elements. This means that your algorithm is O(<em>n</em><sup>2</sup>) for no good reason. What you should do instead is to manually iterate just the required part of the input in each iteration using <code>for</code>. Something like:</p>\n\n<pre><code>double sum = 0;\nfor (int i = 0; i < actualFrameSize; i++)\n{\n sum += data[start + i].Y;\n}\n</code></pre>\n\n<p>(I don't like using <code>GetRange()</code> for this, as in tinstaafl's answer, because it unnecessarily copies the frame into a new list.)</p>\n\n<p>If <code>frameSize</code> is large, another optimization would be not to recompute the sum of the frame for each index. Instead, just add the item from the front and subtract the item from the back:</p>\n\n<pre><code>public PointPairList GetMovingAverage(int frameSize, PointPairList data)\n{\n var movAvgPoints = new PointPairList();\n\n //Before zero\n int currentFrameSize = frameSize/2;\n double sum = data.Take(currentFrameSize).Sum(p => p.Y);\n\n //Smooth each point in the list\n for (int i = 0; i < data.Count; i++)\n {\n int removed = i - (frameSize/2) - 1;\n int added = i + (frameSize/2);\n\n if (removed >= 0)\n {\n sum -= data[removed].Y;\n currentFrameSize--;\n }\n if (added < data.Count)\n {\n sum += data[added].Y;\n currentFrameSize++;\n }\n\n movAvgPoints.Add(new PointPair(data[i].X, sum/actualFrameSize));\n }\n\n return movAvgPoints;\n}\n</code></pre>\n\n<p>If the length of <code>data</code> is <em>n</em> and <code>frameSize</code> is <em>f</em>, then the previous algorithm would be O(<em>fn</em>), but the improved one just O(<em>n</em>).</p>\n\n<hr>\n\n<p>Another thing: there is usually no need to create types that derive from <code>List</code>, just use <code>List<PointPair></code> directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:50:13.217",
"Id": "66145",
"Score": "0",
"body": "Thanks svick, good info, I will probably try to squeeze out every little bit, however the PointPairList is not my code so cannot change."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:41:21.777",
"Id": "39481",
"ParentId": "39439",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "39481",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T02:33:34.243",
"Id": "39439",
"Score": "9",
"Tags": [
"c#",
"performance",
"linq",
"statistics"
],
"Title": "Moving average calculation"
}
|
39439
|
<p>Code review for best practices, optimizations, code cleanup etc. Also requesting verification of the complexity: O(row*row*col).</p>
<pre><code>/**
* Contains coordinates of the
* topMost left, of matrix, obtained by getRowOne and colRowOne
* bottomMost right, of matrix, obtained by getRowTwo and getColTwo
*
* @author javadeveloper
*/
final class RectangleCoord {
private final int rowOne;
private final int colOne;
private final int rowTwo;
private final int colTwo;
public RectangleCoord(int rowOne, int colOne, int rowTwo, int colTwo) {
this.rowOne = rowOne;
this.colOne = colOne;
this.rowTwo = rowTwo;
this.colTwo = colTwo;
}
public int getRowOne() {
return rowOne;
}
public int getColOne() {
return colOne;
}
public int getRowTwo() {
return rowTwo;
}
public int getColTwo() {
return colTwo;
}
}
/**
* Returns the maximum rectangle in the matrix
*
* Complexity:
* O(row2 * col)
*
* @author javadeveloper
*/
public final class MaximumSumRectangeInMatrix {
// made this utility class non-instantiable
private MaximumSumRectangeInMatrix() { }
private static class MaxSubArray {
int start;
int end;
int maxSum;
public MaxSubArray(int start, int end, int maxSum) {
this.start = start;
this.end = end;
this.maxSum = maxSum;
}
}
private static MaxSubArray maxSubArraySum(int[] a) {
assert a != null && a.length > 0;
int max = a[0];
int currSum = a[0];
int start = 0;
int end = 0;
for (int i = 1; i < a.length; i++) {
currSum = currSum + a[i];
if (a[i] > currSum) {
start = i;
currSum = a[i];
}
if (currSum > max) {
max = currSum;
end = i;
}
}
return new MaxSubArray(start, end, max);
}
/**
* Returns the RectangleCoord object containing the maximum
* rectangle in the matrix.
*
* @param The input matrix.
* @return The rectanglecoor object containing the coordinates of the maximum sub matrix
*/
public static RectangleCoord calMaxRectangle(int[][] m) {
if (m.length == 0 || m[0].length == 0) {
throw new IllegalArgumentException("The matrix should be non empty");
}
int max = Integer.MIN_VALUE;
int rowOne = 0;
int colOne = 0;
int rowTwo = 0;
int colTwo = 0;
for (int fromRow = 0; fromRow < m.length; fromRow++) {
int[] temp = new int[m[0].length];
for (int toRow = fromRow; toRow < m.length; toRow++) {
for (int col = 0; col < m[0].length; col++) {
temp[col] = temp[col] + m[toRow][col];
}
MaxSubArray maxSubArrayCoord = maxSubArraySum(temp);
if (maxSubArrayCoord.maxSum > max) {
max = maxSubArrayCoord.maxSum;
rowOne = fromRow;
colOne = maxSubArrayCoord.start;
rowTwo = toRow;
colTwo = maxSubArrayCoord.end;
}
}
}
return new RectangleCoord(rowOne, colOne, rowTwo, colTwo);
}
public static void main(String[] args) {
int[][] m = { {-20, -30, -40, -50},
{ 10, 20, 30, 50},
{ 50, 60, 70, 80},
{-10, -20, -30, -40},
};
RectangleCoord r = calMaxRectangle(m);
System.out.println(r.getRowOne() + " : " + r.getColOne());
System.out.println(r.getRowTwo() + " : " + r.getColTwo());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The begin returned by <code>maxSubArraySub</code> can be wrong as we update <code>start</code> after we've found a good candidate for the maximal sum. This can lead to potential bugs (I am way too lazy to find an actual case where it makes a difference but that should be possible). The solution from <a href=\"http://en.wikipedia.org/wiki/Maximum_subarray_problem\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Maximum_subarray_problem</a> introduces another variable to have a temporary starting point and one for the actual starting point of the maximum found so far.</p>\n\n<p>You can make things much simpler by defining (very simple) classes for 3-tuple and 4-tuple. Make the members private and final and you won't need getters. As the point is just to return multiple values from a function, I don't think there a point in making things too specific and I'd rather have the class and the members have simple names.</p>\n\n<p>You have a typo in your class name and it's especially annoying in Java where the file name has to match ;-)</p>\n\n<p>You could make your code a bit more robust by asserting that all rows have same length.</p>\n\n<p>In your code, the comment about complexity is wrong. The one is your stackoverflow question is right, it is indeed N*N*M :-)</p>\n\n<p>Here's what I've done :</p>\n\n<pre><code>final class Tuple4 {\n public final int a;\n public final int b;\n public final int c;\n public final int d;\n\n public Tuple4(int a, int b, int c, int d) {\n this.a = a;\n this.b = b;\n this.c = c;\n this.d = d;\n }\n}\n\nfinal class Tuple3 {\n public final int a;\n public final int b;\n public final int c;\n\n public Tuple3(int a, int b, int c) {\n this.a = a;\n this.b = b;\n this.c = c;\n }\n}\n\n/**\n * Returns the maximum rectangle in the matrix\n *\n * @author javadeveloper\n */\npublic final class MaximumSumRectangleInMatrix {\n\n // made this utility class non-instantiable\n private MaximumSumRectangleInMatrix() { }\n\n private static Tuple3 maxSubArraySum(int[] a) {\n assert a != null && a.length > 0;\n\n int max = a[0];\n int currSum = a[0];\n\n int start = 0;\n int start_tmp = 0;\n int end = 0;\n\n for (int i = 1; i < a.length; i++) {\n if (currSum < 0) {\n start_tmp = i;\n currSum = a[i];\n } else {\n currSum += a[i];\n }\n if (currSum > max) {\n max = currSum;\n start = start_tmp;\n end = i;\n }\n }\n return new Tuple3(start, end, max);\n }\n\n\n /**\n * Returns the Tuple4 object containing the maximum\n * rectangle in the matrix.\n *\n * @param The input matrix.\n * @return The rectanglecoor object containing the coordinates of the maximum sub matrix\n */\n public static Tuple4 calMaxRectangle(int[][] m) {\n if (m.length == 0 || m[0].length == 0) {\n throw new IllegalArgumentException(\"The matrix should be non empty\");\n }\n\n int max = Integer.MIN_VALUE;\n int a = 0;\n int b = 0;\n int c = 0;\n int d = 0;\n\n int lengthRow = m[0].length;\n\n for (int i1 = 0; i1 < m.length; i1++)\n {\n if (lengthRow != m[i1].length)\n throw new IllegalArgumentException(\"Matrix is not square\");\n\n int[] temp = new int[lengthRow];\n for (int i2 = i1; i2 < m.length; i2++)\n {\n for (int j = 0; j < lengthRow; j++)\n temp[j] += m[i2][j];\n\n Tuple3 maxSubArrayCoord = maxSubArraySum(temp);\n\n if (maxSubArrayCoord.c > max) {\n max = maxSubArrayCoord.c;\n a = i1;\n b = maxSubArrayCoord.a;\n c = i2;\n d = maxSubArrayCoord.b;\n }\n }\n }\n return new Tuple4(a,b,c,d);\n }\n\n public static void main(String[] args) {\n int[][] m = { {-20, -30, -40, -50, 50},\n { 10, 20, 30, 50, -10},\n { 50, 60, 70, 80, 30},\n {-10, -20, -30, -40, 60},\n };\n\n Tuple4 r = calMaxRectangle(m);\n System.out.println(\"(\" + r.a + \",\" + r.b + \") ; (\" + r.c + \",\" + r.d + \")\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:26:42.950",
"Id": "39460",
"ParentId": "39443",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T06:28:19.577",
"Id": "39443",
"Score": "1",
"Tags": [
"java",
"matrix",
"dynamic-programming"
],
"Title": "MaxSum sub matrix within a matrix"
}
|
39443
|
<p>Which of these names is better: <code>time.getHours()</code> or <code>time.hours()</code>? And why?</p>
<pre><code>public class Time implements Serializable {
private final int hours;
private final int minutes;
public static Time from(Calendar calendar) {
int hoursIn24HourFormat = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
return new Time(hoursIn24HourFormat, minutes);
}
public Time(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
}
// or may be getHours() name is better?
public int hours() {
return hours;
}
// or may be getMinutes() name is better?
public int minutes() {
return minutes;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Time)) {
return false;
}
Time other = (Time) obj;
return (hours == other.hours) &&
(minutes == other.minutes);
}
@Override
public int hashCode() {
return toMinutesOfDay();
}
private int toMinutesOfDay() {
return hours * 60 + minutes;
}
@Override
public String toString() {
return twoDigitString(hours) + ":" + twoDigitString(minutes);
}
private static String twoDigitString(int timeComponent) {
return (timeComponent < 10)
? ("0" + timeComponent)
: String.valueOf(timeComponent);
}
public boolean before(Time time) {
return toMinutesOfDay() < time.toMinutesOfDay();
}
public boolean after(Time time) {
return toMinutesOfDay() > time.toMinutesOfDay();
}
public boolean within(Time fromIncluded, Time toIncluded) {
return (!fromIncluded.after(this)) && (!this.after(toIncluded));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It is a matter of taste, so there is no 'better'. But more common seams to be <code>time.getHours();</code> because often the conventions of <a href=\"http://en.wikipedia.org/wiki/JavaBeans#JavaBean_conventions\" rel=\"nofollow\">JavaBean</a> are used.</p>\n\n<p>If you work in a team, I would discuss the naming conventions to use with them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T07:21:34.410",
"Id": "66058",
"Score": "0",
"body": "Coming from a fair amount of time spent with Java and Android, I would second this. You usually only see something like `time.hours` if `hours` is a public member."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T07:00:15.873",
"Id": "39445",
"ParentId": "39444",
"Score": "4"
}
},
{
"body": "<p>I'd name the class <code>TimeOfDay</code> to be absolutely clear about its purpose.</p>\n\n<p>Consider adding validation to the constructor (0 ≤ hour ≤ 23 and 0 ≤ minutes ≤ 59).</p>\n\n<p>Because <code>before()</code> and <code>after()</code> are <a href=\"https://codereview.stackexchange.com/questions/39399/naming-of-predicate-methods\">predicates</a>, I'd rename them to <code>isBefore(TimeOfDay t)</code> and <code>isAfter(TimeOfDay t)</code>.</p>\n\n<p>I prefer <code>getHours()</code> over <code>hours()</code>.</p>\n\n<p>If you prefer <code>hours()</code>, you <em>might</em> consider just exposing <code>public final int hours, minutes;</code> instead. Normally, you want to reserve the flexibility to change the internal representation of your object (for example, to store just <code>minutesOfDay</code> instead of <code>hours</code> and <code>minutes</code>). However, since those fields are <code>final</code>, and you're more or less committed to the representation due to serialization, there's not much to be gained by wrapping the value in a method, other than consistency with tradition, and you would already violate tradition slightly anyway by choosing <code>hours()</code> over <code>getHours()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T07:22:14.193",
"Id": "39446",
"ParentId": "39444",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39446",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T06:52:47.167",
"Id": "39444",
"Score": "4",
"Tags": [
"java",
"datetime"
],
"Title": "Proper naming for a Time class"
}
|
39444
|
<p>I have the following code:</p>
<pre><code>static void TimerElapsed(object sender, ElapsedEventArgs e)
{
foreach (BIGService bigService in runningServices)
{
if (!bigService.ExecutedToday)
{
int executionResult = bigService.Execute();
string serviceName = bigService.ToString();
if (executionResult == 0)
{
EventLogger.WriteToEventLog("Success");
}
else
{
EventLogger.WriteToEventLog("Failure");
}
}
}
}
</code></pre>
<p>where <code>BIGService</code> is an Abstract class, that has 5 descendants (5 individual service classes with this common parent). The enclosing timer's interval is 7200. So it elapses in every 2 hours.</p>
<p>All services must be run only once a day. Therefore I created a <code>bool ExecutedToday</code> property and <code>void SetAsExecuted</code> method.</p>
<p>My question is: where do you recommend I should call the <code>SetAsExecuted</code> method? Which way is more subservient? In the end of the <code>Execute()</code> method itself or in my copied code at the end of the <code>if</code> clause?</p>
<p>(Similar situations have happened to me several times, I just now have the time to ask other's opinion)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:52:55.800",
"Id": "66083",
"Score": "1",
"body": "Why not just set up a Scheduled Task on the machine this needs to run under?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T09:59:57.987",
"Id": "66506",
"Score": "0",
"body": "I don't really want to use that. I want my program to manage itself."
}
] |
[
{
"body": "<p>As your code stands now it looks to me as if the timer has some responsibilities it shouldent have.</p>\n\n<p>My suggestion would be to either move all the timer information to your timer, including bigService.ExecutedToday and SetAsExecuted OR you move all that logic inside the service. I would go for the latter since that would be more in line with the \"Tell dont ask\" principle. </p>\n\n<p>The code in the timer would look like this:</p>\n\n<pre><code>static void TimerElapsed(object sender, ElapsedEventArgs e)\n{\n foreach (BIGService bigService in runningServices)\n { \n bigService.Execute(); \n }\n}\n</code></pre>\n\n<p>In your BigService method you contain the logging and wether or not that service can be run at the time it is requested. </p>\n\n<p>One more thing: I would make an Enum to store the 0 value for executionResult, at a later date it might not be clear to you what 0 actually means</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:42:41.017",
"Id": "66096",
"Score": "0",
"body": "Or `bool` instead of an Enum, if you want a boolean \"succeeded-or-failed\" result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:47:52.263",
"Id": "66217",
"Score": "0",
"body": "@CrisW Good point. If its a succeed/fail scenario there is really no need for an enum and a bool would give the desired clarity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T10:04:34.177",
"Id": "66507",
"Score": "0",
"body": "It's not an easy 1 bit scenario, there are more branches as results. Actually that is Enum, just here in this code is 0 (just for the sake of simplicity). Thanks a lot anyway!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:22:32.153",
"Id": "39449",
"ParentId": "39447",
"Score": "4"
}
},
{
"body": "<p>I prefer it if classes manage their own state as much as possible: that makes it difficult to use them incorrectly.</p>\n\n<p>For example, in the code above you are able to 'forget' to call SetAsExecuted and can thus write a bug.</p>\n\n<p>So if ExecutedToday is a property of Service then it's better if Service manages that property state.</p>\n\n<pre><code>Service\n{\n DateTime recentlyExecuted;\n public bool ExecutedToday\n { get { return (DateTime.Now - recentlyExecuted) < new TimeSpan(1,0,0,0); } }\n public int Execute() {\n int executionResult = OnExecute(); // do the work\n if (executionResult == 0)\n {\n EventLogger.WriteToEventLog(\"Success\");\n }\n else\n {\n EventLogger.WriteToEventLog(\"Failure\");\n }\n recentlyExecuted = DateTime.Now; // or, only set if execution successful?\n return executionResult;\n }\n protected abstract int OnExecute(); // do subclass-specific work for Execute\n}\n</code></pre>\n\n<p>If you want to ensure that Execute sets the property, then it should be a <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">template method</a> as coded above: otherwise (if Execute is abstract) then you're counting on every subclass to remember to set the property in its override of the Execute method.</p>\n\n<p>Alternatively you can maintain the recentlyExecuted property outside the Service class:</p>\n\n<pre><code>static Map<BIGService, DateTime> recentlyExecuted = new Map<BIGService, DateTime>();\n\nstatic void TimerElapsed(object sender, ElapsedEventArgs e)\n{\n foreach (BIGService bigService in runningServices)\n {\n if (recentlyExecuted.ContainsKey(service) &&\n ((DateTime.Now - recentlyExecuted[service]) < new TimeSpan(1,0,0,0)))\n continue; // already executed today\n int executionResult = bigService.Execute();\n recentlyExecuted[service] = DateTime.Now; // or, only set if execution successful?\n string serviceName = bigService.ToString();\n if (executionResult == 0)\n {\n EventLogger.WriteToEventLog(\"Success\");\n }\n else\n {\n EventLogger.WriteToEventLog(\"Failure\");\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:59:09.097",
"Id": "39452",
"ParentId": "39447",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39449",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:06:06.313",
"Id": "39447",
"Score": "2",
"Tags": [
"c#"
],
"Title": "How should I set a daily method as executed, from inside or from outside?"
}
|
39447
|
<p>I have client's methods that processes a large SQL query. I wouldn't like to do that through getting whole query result to memory, but process it in batches. It entails with exposing JDBC API to client's code. I think that this code could be refactored much better.</p>
<pre><code> //client's method
m_jdbcManager = JdbcManagerUtil.getInstance();
m_tupleManager = DbTupleManager.getInstance();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = m_jdbcManager.getConnection();
connection.setAutoCommit(false);
statement = connection
.prepareStatement(Statements.SELECT_RIGHT_TUPLES);
statement.setInt(1, id);
statement.setFetchSize(JdbcManagerUtil.FETCH_SIZE);
resultSet = statement.executeQuery();
while (resultSet.next()) {
Tuple tuple = (Tuple) m_tupleManager
.readObject(resultSet);
//process tuple, invokes methods from client class
}
connection.setAutoCommit(true);
JdbcManagerUtil.closeEverything(connection, statement, resultSet);
} catch (<exceptions>) {
}
</code></pre>
<p>I tried to expose method that returns <code>ResultSet</code>, but after processing, there must be released resources <code>Connection</code>, <code>PreparedStatement</code> and <code>ResultSet</code>.
JDBC 4 and PostreSQL database.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:32:16.170",
"Id": "66093",
"Score": "0",
"body": "You should update your question and tell us which JDBC Client/server you are using...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:23:34.787",
"Id": "66125",
"Score": "0",
"body": "`setAutoCommit(true)` and `closeEverything` needs to be in a `finally` block. Outherwise, you may leak resources or break down codes that rely on `autoCommit` being `true`."
}
] |
[
{
"body": "<p>Your assumption that the entire dataset is read in to memory is not necessarily accurate. The JDBC clients I have worked with (DB2, MS-SQLServer, Sybase, Oracle, etc.) each default to, or have an option to limit the size of the client-side buffer. You only have a small amount of data on the actual client, and the ResultSet process fetches more data when you iterate through it.</p>\n\n<p>There is no need to add another level of buffering. Are you sure the data is <strong>all</strong> being returned? Have you inspected the configuration options for <strong>your</strong> JDBC Client?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:49:47.860",
"Id": "66097",
"Score": "0",
"body": "Thanks, you're right. I mean if I create method \nList<Object> getTuples(); in my JdbcManager class that manages queries, then memory problem will occur. So I would like to process row by row. But then it is difficult to hide implementation of getting each row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:32:51.370",
"Id": "66132",
"Score": "0",
"body": "You can return an `iterator`. Don't forget to `close` resources. (I would guess after the last `next()` but you might want to check again in `finalize` to be sure)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:39:27.400",
"Id": "66138",
"Score": "0",
"body": "Or return a `interface ClosableIterator<T> extends Iterator<T>, Closeable {}`, and let the caller do the `close`ing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:13:05.320",
"Id": "39464",
"ParentId": "39448",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:12:14.323",
"Id": "39448",
"Score": "2",
"Tags": [
"java",
"jdbc"
],
"Title": "How to hide implementation of JDBC while processing large query in client's code?"
}
|
39448
|
<p>I have written a singleton module which is to be used for some future modifications on <code>.chart</code> elements. Modification functions, such as <code>colorArgumentButtons()</code> are called recursively so that I don't have to iterate over all <code>.chart</code> elements in all functions.</p>
<p>Is my use of <code>_</code> for private "class vars" proper? Otherwise they may conflict with my local vars.</p>
<p>Am I using the revealing module pattern correctly and is my namespace implementation okay? Feel free to comment on bad design choices!</p>
<pre><code>var SuperHappy = (function (_parent, $) {
var _my = _parent.Chart = _parent.Chart || {};
// default settings
var _settings = {
autoFind: true,
chartSelector: '.chart'
};
// jQuery vars
var _$charts = $();
_my.init = function (options) {
/// <summary>
/// Initializes the module.
/// </summary>
/// <param name="options">Custom JSON options</param>
_settings = $.extend(_settings, options);
if (_settings.autoFind) {
_my.findCharts();
}
};
var _applyFunctionToAll = function (func, $charts) {
/// <summary>
/// Applies the supplied function for each chart element in the collection.
/// </summary>
/// <param name="func">Function to be applied</param>
/// <param name="$charts">Optional chart collection to apply function on</param>
if (typeof $charts === 'undefined' && _$charts !== $()) {
$charts = _$charts;
}
if ($charts.length === 1) {
return false;
}
$charts.each(function () { // can this be converted to a for loop?
func($(this));
});
return true;
};
_my.colorArgumentButtons = function (color, $chart) {
/// <summary>
/// Colors all argument buttons.
/// </summary>
/// <param name="color">Color to be used</param>
/// <param name="$chart"></param>
if (_applyFunctionToAll(_my.colorArgumentButtons.bind(null, color), $chart)) {
return;
}
$chart.find('button').css('background-color', color);
};
_my.findCharts = function (selector) {
/// <summary>
/// Finds all chart elements.
/// </summary>
/// <param name="selector">Optional CSS selector for finding chart elements</param>
selector = typeof selector !== 'undefined' ? selector : _settings.chartSelector;
_$charts = $(selector);
};
return _parent;
})(SuperHappy || {}, jQuery);
jQuery(document).ready(function ($) {
SuperHappy.Chart.init();
SuperHappy.Chart.colorArgumentButtons('#f00');
});
</code></pre>
<p><a href="http://jsfiddle.net/JrwRN/" rel="nofollow">http://jsfiddle.net/JrwRN/</a></p>
|
[] |
[
{
"body": "<p>I think you are overdoing the underscores, you will find that conflicts will be rare.</p>\n\n<p>Furthermore, I can understand that you want to centralize the iteration over the chart elements, but why would you want to do that recursively, it does not make much sense to me. </p>\n\n<p>If you drop underscores and opt out of recursive iteration, your iterator becomes simpler:</p>\n\n<pre><code> //Applies the supplied function for each chart element in the collection.\n var applyFunction = function ( f )\n {\n $charts.each(function (){ f($(this)); });\n };\n</code></pre>\n\n<p>This could be converted to a for loop as per your comment</p>\n\n<pre><code> //Applies the supplied function for each chart element in the collection.\n var applyFunction = function ( f )\n {\n for( var i = 0, length = $charts.length; i < length ; i++ ){\n f( $charts[i] );\n }\n };\n</code></pre>\n\n<p>Then, <code>colorArgumentButtons</code> becomes simpler as well:</p>\n\n<pre><code> // Colors all argument buttons.\n my.colorArgumentButtons = function (color)\n {\n applyFunction( function( $chart )\n {\n $chart.find('button').css('background-color', color);\n });\n };\n</code></pre>\n\n<p>You will notice that I reduced the comments to a one line comment. When you have almost as much lines of comment as code, then you are doing it wrong.</p>\n\n<p>A minor side note on </p>\n\n<pre><code>selector = typeof selector !== 'undefined' ? selector : settings.chartSelector;\n</code></pre>\n\n<p>this could simply be </p>\n\n<pre><code>selector = selector || settings.chartSelector;\n</code></pre>\n\n<p>All in all, I refactored the code into this ( untested ):</p>\n\n<pre><code>var SuperHappy = (function (parent, $) {\n\n var my = parent.Chart = parent.Chart || {},\n // default settings\n settings = {\n autoFind: true,\n chartSelector: '.chart'\n },\n // jQuery vars\n $charts = $();\n\n //Applies the supplied function for each chart element in the collection.\n var applyFunction = function ( f )\n {\n $charts.each(function (){ func($(this)); });\n };\n\n my.init = function (options) \n {\n settings = $.extend(settings, options);\n if (settings.autoFind) {\n my.findCharts();\n }\n };\n\n /// Colors all argument buttons.\n my.colorArgumentButtons = function (color)\n {\n applyFunction( function( $chart )\n {\n $chart.find('button').css('background-color', color);\n });\n };\n\n // Finds all chart elements.\n my.findCharts = function (selector)\n {\n selector = selector || settings.chartSelector;\n $charts = $(selector);\n };\n\n return parent;\n\n})(SuperHappy || {}, jQuery);\n\njQuery(document).ready(function ($) {\n SuperHappy.Chart.init();\n SuperHappy.Chart.colorArgumentButtons('#f00');\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T19:08:19.383",
"Id": "66689",
"Score": "0",
"body": "Thank you for your input. However, conflicts are there since I have a private `_$charts` and a local `$charts`. Actually, you eliminated some of my functionality by throwing away arguments for some of my methods. In my updated code I put all privates in an object `_`. I also gave up on the recursive implementation and solved it with an anonymous function. I'll show my updated code tomorrow, and I'll be sure to use your neat `selector = selector || settings.chartSelector` -- I did not know that. And yeah, comments are written so that Visual Studio will pick them up: not my choice. ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T15:42:58.017",
"Id": "39658",
"ParentId": "39451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T09:55:15.950",
"Id": "39451",
"Score": "0",
"Tags": [
"javascript",
"revealing-module-pattern"
],
"Title": "Singleton model for modifying future .chart elements"
}
|
39451
|
<p>In a payment application a day before and at the same time with some payments some messages(email) needs to be sent.
I have a DTO (called <code>EscrowPayment</code>, projected from some entity) from which I generate and send two similar `messages.</p>
<p>I look for advice specifically on the following issues with the code I ended up:</p>
<ul>
<li>Copy-pasted code.</li>
<li>Type suffix in identifiers. eg: <code>nominalAmountStr</code></li>
<li>Static utility methods <code>formatInteger</code> etc (Used application wide).</li>
<li>String constants in code. But because they are parameterized by position and not by name; if I extract them to a configuration file as they are,
I wouldn't know in which order I should be giving parameters to <code>String.format</code>.</li>
</ul>
<p>Here is the code; it is sanitized and translated, but issues are clearly identifiable:</p>
<pre><code>public class EscrowPaymentMessageServiceImpl {
private JavaMailSender mailSender;
// .....
@Override
public void escrowPaymentWillBeDone(EscrowPayment escrowPayment) throws BusinessLayerException {
try {
String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));
String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), "dd/MM/yyyy");
String interestRateStr = format(escrowPayment.getInterestRate(), "0.00###");
String paymentAmountStr = format(escrowPayment.getPaymentAmount());
String messageText = String
.format("BLAH BLAH some security with ID %s of nominal value EUR %s "
+ "at date %s BLAH your account with number 1234567890 will be debited to pay "
+ "EUR %s coupon payment for %%%s interest.",
escrowPayment.getSecurityId(), nominalStr, paymentDateStr,
interestRateStr, paymentAmountStr);
sendMessage(messageText);
} catch (MessagingException e) {
getLog().error("An error occured while sending the email:", e);
throw new BusinessLayerException("EscrowPaymentMessage.MessageCouldNotBeSent", e);
}
}
@Override
public void escrowPaymentIsDone(EscrowPayment escrowPayment) throws BusinessLayerException {
try {
String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));
String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), "dd/MM/yyyy");
String paymentAmountStr = format(escrowPayment.getPaymentAmount());
String messageText = String.format("BLAH BLAH at date %s the security with ID %s of nominal value EUR %s "
+ "BLAH your account with number 1234567890 has been debited to pay EUR %s." ,
paymentDateStr, escrowPayment.getSecurityId(), nominalStr, paymentAmountStr);
sendMessage(messageText);
} catch (MessagingException e) {
getLog().error("An error occured while sending the email:", e);
throw new BusinessLayerException("EscrowPaymentMessage.MessageCouldNotBeSent", e);
}
}
private void sendMessage(messageText) throws MessagingException {
//....
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:18:47.397",
"Id": "66100",
"Score": "0",
"body": "There's not much I can see, is using a template system like [StringTemplate](http://www.stringtemplate.org/) an option?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T08:21:13.727",
"Id": "66497",
"Score": "0",
"body": "Thanks @Bobby. I checking it out, but introducing a new dependency would be a little too costly for me *in this occasion*."
}
] |
[
{
"body": "<p>This strikes me as an occasion where a custom method with positional format indexing may help <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html\" rel=\"nofollow\">(Formatter <code>argument_index</code>)</a>. It is a little-known feature of Java's String.format / Formatter class, that you can reference values by their position. Consider the following methods:</p>\n\n<pre><code>@Override\npublic static final String formatEscrowPayment(String format, EscrowPayment escrowPayment) {\n String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));\n String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), \"dd/MM/yyyy\");\n String interestRateStr = format(escrowPayment.getInterestRate(), \"0.00###\");\n String paymentAmountStr = format(escrowPayment.getPaymentAmount());\n return String.format(format, \n escrowPayment.getSecurityId(), // 1\n nominalStr, // 2\n paymentDateStr, // 3\n interestRateStr, // 4\n paymentAmountStr); // 5\n\n}\n\nprivate static final void sendExcrowMessage(String template, ExcrowPayment escrow) throws BusinessLayerException {\n try {\n String messageText = formatEscrowPayment(template, escrow);\n sendMessage(messageText);\n } catch (MessagingException e) {\n getLog().error(\"An error occured while sending the email:\", e);\n throw new BusinessLayerException(\"EscrowPaymentMessage.MessageCouldNotBeSent\", e);\n }\n}\n\n@Override\npublic void escrowPaymentWillBeDone(EscrowPayment escrowPayment) throws BusinessLayerException {\n sendEscrowMessage(\"BLAH BLAH some security with ID %1$s of nominal value EUR %2$s \"\n + \"at date %3$s BLAH your account with number 1234567890 will be debited to pay \"\n + \"EUR %5$s coupon payment for %%%4$s interest.\",\n escrowPayment);\n\n@Override\npublic void escrowPaymentIsDone(EscrowPayment escrowPayment) throws BusinessLayerException {\n sendEscrowMessage(\"BLAH BLAH at date %3$s the security with ID %1$s of nominal value EUR %2$s \"\n + \"BLAH your account with number 1234567890 has been debited to pay EUR %2$s.\" ,\n}\n</code></pre>\n\n<p>Note how the substitution values are handled by their positions.... the <code>%1$s</code> references the first format value as a string. The <code>%3$s</code> references the 3rd value. You can change the order of the positional fields without having to change the positions of the values in the actual format call. Have a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html\" rel=\"nofollow\">look at the documentation</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T08:28:44.303",
"Id": "66499",
"Score": "0",
"body": "Thanks. This is what was I trying to do in the first place. But I forgot about argument indexes in format strings, and forgot that I forgot. But this is what SE is for. I'll wait for another day or two before accepting, in case someone comes up with another answer that *I don't know that I don't know* :)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T07:55:22.670",
"Id": "39587",
"ParentId": "39453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39587",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T10:18:50.263",
"Id": "39453",
"Score": "3",
"Tags": [
"java"
],
"Title": "Code duplication when converting DTO to String messages"
}
|
39453
|
<p>PHP's <code>eval()</code> is general considered insecure with any user input.</p>
<p>However, with filtering of input (i.e. <code>[-+/*0-9]</code>) you can make <code>eval()</code> secure for a small subset of PHP; mathematical expressions.</p>
<p>I've tried to think of a way to extend that by allowing a limited set of math functions and I believe I've found a secure way of doing it.</p>
<pre><code>function expression($expression) {
static $function_map = array(
'floor' => 'floor',
'ceil' => 'ceil',
'round' => 'round',
'sin' => 'sin',
'cos' => 'cos',
'tan' => 'tan',
'asin' => 'asin',
'acos' => 'acos',
'atan' => 'atan',
'abs' => 'abs',
'log' => 'log',
'pi' => 'pi',
'exp' => 'exp',
'min' => 'min',
'max' => 'max',
'rand' => 'rand',
'fmod' => 'fmod',
'sqrt' => 'sqrt',
'deg2rad' => 'deg2rad',
'rad2deg' => 'rad2deg',
);
// Remove any whitespace
$expression = strtolower(preg_replace('~\s+~', '', $expression));
// Empty expression
if ($expression === '') {
trigger_error('Empty expression', E_USER_ERROR);
return null;
}
// Illegal function
$expression = preg_replace_callback('~\b[a-z]\w*\b~', function($match) use($function_map) {
$function = $match[0];
if (!isset($function_map[$function])) {
trigger_error("Illegal function '{$match[0]}'", E_USER_ERROR);
return '';
}
return $function_map[$function];
}, $expression);
// Invalid function calls
if (preg_match('~[a-z]\w*(?![\(\w])~', $expression, $match) > 0) {
trigger_error("Invalid function call '{$match[0]}'", E_USER_ERROR);
return null;
}
// Legal characters
if (preg_match('~[^-+/%*&|<>!=.()0-9a-z,]~', $expression, $match) > 0) {
trigger_error("Illegal character '{$match[0]}'", E_USER_ERROR);
return null;
}
return eval("return({$expression});");
}
</code></pre>
<p>It's use would be simple: `$result = expression('floor(3 / 2)') and anything but math/boolean operators, numbers and a limited set of functions should be filtered out.</p>
<p>I can't find a way of hacking this <code>expression()</code> function, but I'd really like to have a second opinion on this.</p>
<p>Is the above <code>expression</code> function secure for user input?</p>
|
[] |
[
{
"body": "<p>It looks pretty reasonable to me. A couple of points:</p>\n\n<ol>\n<li><p>You seem to be assuming that a function start with a letter. Functions CAN start with an underscore. Are you sure there is no such function that can be exploited?</p></li>\n<li><p>The regex in the section 'Invalid function calls' seems like it could be simpler. You are trying to check that any 'word' ends with a '(', is this right? If so, I don't think you need the second <code>\\w</code></p></li>\n</ol>\n\n<p>Finally although this seems like a good job, the ideally ideal way to do something like this would be to make your own tokenizer. A tokenizer looks at a string char by char and decides at each point whether it's looking at part of an identifier, an operator, etc. You would simply need to call your checks at each point that it decides it has identified a complete token. The advantage of this is that it would be easy to extend the syntax you accept and if needed to make translations from the language you accept to valid PHP for <code>eval()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:59:13.587",
"Id": "66085",
"Score": "1",
"body": "Re: 1. It shouldn't be a problem as the legal characters check does not recognize underscore as a legal character."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:00:59.557",
"Id": "66087",
"Score": "0",
"body": "Re: 2. The check is to find words that do not end with a `(`. The second `\\w` is required as without it, `abc(` would match as `ab`. The `\\w` ensures it matches at word boundary. Which is not to say there might be a more better regex that does the same job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:27:48.337",
"Id": "66102",
"Score": "0",
"body": "Obviously you are right about 1. I may have tested 2 wrongly, will check"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:37:30.933",
"Id": "39462",
"ParentId": "39454",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T10:32:20.897",
"Id": "39454",
"Score": "5",
"Tags": [
"php",
"security"
],
"Title": "Secure math expressions using PHP eval()"
}
|
39454
|
<p>I have the following contact form, using PHP, JS and a bit of Ajax. I want to make sure that it is secure.</p>
<pre><code><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
ob_start();
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message']) && isset($_POST['token']))
{
if($_SESSION['token'] != $_POST['token'])
{
$response = "0";
}
else
{
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "email@here.com";
$subject = "New Message From: $name";
$message = "$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))
$response = ($mailed) ? "1" : "0";
else
$response = ($mailed) ? "<h2>Success!</h2>" : "<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
}
else
{
echo "Form data error!";
}
ob_flush();
die();
}
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title>Contact us | Website Name</title>
<meta name="description" content="">
<?php include ("assets/includes/header.inc"); ?>
</head>
<body>
<header id="headerWrapper">
<div id="headerContent">
<div id="headerLogo"><!--Logo-->
<?php include ("assets/includes/header-logo.inc"); ?>
</div>
<nav><!--Main Menu-->
<ul id="mainMenu">
<?php include ("assets/includes/menu.inc"); ?>
</ul>
</nav>
</div>
</header>
<!--Header (small screens only)-->
<?php include ("assets/includes/second-header.inc"); ?>
<div id="page"><!--Page Container-->
<div id="contactPage" class="wrapper">
<div class="content">
<!--Contact Form-->
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<form id="contactForm" action="contact.php" method="post" name="contactForm">
<input id="token" type="hidden" value="<?php echo $token; ?>" />
<div class="name">
<label>Your Name</label>
<input id="name" type="text" placeholder="Enter Name" required>
</div>
<div class="email">
<label>Email Address</label>
<input id="email" type="email" placeholder="Enter Email" required>
</div>
<div class="message">
<label>Message</label>
<textarea id="message" required></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$submit = $form.find('button[id="submit"]'),
token_value = $form.find('input[id="token"]').val(),
name_value = $form.find('input[id="name"]').val(),
email_value = $form.find('input[id="email"]').val(),
message_value = $form.find('textarea[id="message"]').val(),
url = $form.attr('action');
/* send the data using post */
var posting = $.post(url, {
token : token_value,
name : name_value,
email : email_value,
message : message_value,
ajax : 1
});
posting.done(function(data) {
$form.find('span.error').remove();
if (data == "1") {
/*Change the button text.*/
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$("#submit").attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 20px 5px; color: #bd3d3d" class="error">Failed to send the message, please try again later.</span>');
/*Change the button text.*/
$submit.text('Try Again');
}
});
});
</script>
<!--Contact Details Section-->
<div id="contactDetails">
<div>
<h3><strong>Contact Details</strong></h3>
<br>
<p><strong>Telephone:</strong> +44 00 0000000</p>
<p><strong>Email:</strong> email@email.com</p>
<!--Phone contact buttons-->
<div class="hidden">
<a href="tel:0044000000000">Tap to call us</a>
<a href="sms:0044000000000">Tap to send us a SMS</a>
</div>
</div>
<!--Social Icons-->
<br><div class="socialbar">
<p><strong>Find us on:</strong></p>
<a href="#" target="blank" class="icon-facebook"></a>
<a href="#" target="blank" class="icon-linkedin"></a>
<a href="#" target="blank" class="icon-twitter"></a>
<a href="#" target="blank" class="icon-youtube"></a>
</div>
</div>
</div>
</div>
<!--Footer-->
<footer id="footer">
<?php include ("assets/includes/footer.inc"); ?>
</footer>
</div><!--The End Of The Page-->
<!--Scripts Links-->
<?php include ("assets/includes/scripts.inc"); ?>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T20:21:56.800",
"Id": "66977",
"Score": "0",
"body": "Why do you have quotes around your integers?"
}
] |
[
{
"body": "<p>The form seems to be OK, but mixing all of the code in one file is not a best-practice.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Some tips on code separation:</p>\n\n<ul>\n<li>I would suggest using any template system for html/php code\nseparation. For example Smarty. </li>\n<li>Also, it would be easier for you to\nmaintain your code if you follow the MVC pattern.</li>\n<li>Moving the js code\nto a separate file and loading it would also separate you js logic\nfrom template.</li>\n<li>As @SilverlightFox mentioned, make sure you protect you .inc file. This could be done like in <a href=\"https://stackoverflow.com/questions/13968901/folders-protection-in-php/13969167#13969167\">this</a> answer of mine.</li>\n</ul>\n\n<p>Some other tips:</p>\n\n<ul>\n<li>I would rather use <code>$token = md5(time());</code> than <code>$token = md5(uniqid(rand(), TRUE));</code></li>\n<li>Using <code>ob_start(); ... ob_end_flush();</code> functions is often confusing as it prevents other files from rendering any output.</li>\n<li><strong>Always</strong> use curly brackets for if constructions: <code>if (isset($_POST['ajax'])) { ... } else { ... }</code>. Otherwise you might confuse the logic/flow of the application when you'll be re factoring your own code like in 6 month, for example.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:14:50.563",
"Id": "66192",
"Score": "0",
"body": "A note on MD5: Since the 90s issues have been found with that algorithm. Do not use it for anything else than interfacing with legacy systems. To checksum something, the SHA family is often a better solution. To scramble some secret, use a key-stretching function like bcrypt. Using `md5(time())` as a token produces predictable tokens, and can issue multiple identical tokens – this is most obvious if you think of it as a concurrency bug. This is actually far worse in any respect than `uniqid rand`. Otherwise, nice review: +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:17:00.267",
"Id": "66195",
"Score": "0",
"body": "@amon, this is a contact form, not a bank vault. I suppose this would be enough."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:13:00.660",
"Id": "39488",
"ParentId": "39455",
"Score": "2"
}
},
{
"body": "<p>No, I've noticed several issues.</p>\n\n<p>Make sure the stuff in <code>assets/includes/</code> isn't world readable.</p>\n\n<p>e.g. is it possible to view this code by going to <code>www.example.com/assets/includes/second-header.inc</code> (substituting in your domain name of course)?</p>\n\n<p>Also, don't use <code>rand()</code> to generate tokens for secure use. <code>rand()</code> will generate predictable values that can be guessed by an attacker.</p>\n\n<p><a href=\"http://uk3.php.net/rand\" rel=\"nofollow\">The manual</a> states:</p>\n\n<blockquote>\n <p>Caution\n This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using <a href=\"http://uk3.php.net/manual/en/function.openssl-random-pseudo-bytes.php\" rel=\"nofollow\">openssl_random_pseudo_bytes()</a> instead.</p>\n</blockquote>\n\n<p>You need cryptographically secure values for use as tokens.</p>\n\n<p>Also, make sure that the <code>email</code> you are entering in the headers</p>\n\n<pre><code> $headers .= 'From: '.$email . \"\\r\\n\";\n</code></pre>\n\n<p>has new lines and carriage return characters stripped from it to prevent <a href=\"http://en.wikipedia.org/wiki/Email_injection\" rel=\"nofollow\">Email Header Injection</a>.</p>\n\n<p>Otherwise you're good to go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:27:48.953",
"Id": "39491",
"ParentId": "39455",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T10:34:38.360",
"Id": "39455",
"Score": "4",
"Tags": [
"php",
"security",
"ajax",
"form"
],
"Title": "Is this contact form secure?"
}
|
39455
|
<p>I've started writing a small CSV parser class as I needed a method to group a CSV file by a given column.</p>
<pre><code>class CSVParser {
private $FileName;
private $FileHandle;
private $HasHeaderRow = false;
private $RowsToIgnore = array();
public function __construct ($FileName, $Mode = "r") {
$this->FileName = $FileName;
if (($this->FileHandle = fopen($this->FileName, $Mode)) === FALSE)
return false; // that's all your getting for now.
}
public function hasHeaderRow ($Flag = false) {
$this->HasHeaderRow = (bool) $Flag;
}
public function ignoreRows (array $Rows) {
$this->RowsToIgnore = $Rows;
}
public function groupByColumn ($GroupColumn = 0, $RowLength = 1000, $Seperator = ",") {
$CurrentRow = -1;
$Classes = array();
while (($Data = fgetcsv($this->FileHandle, $RowLength, $Seperator)) !== FALSE) {
$CurrentRow++;
// does the csv contain a header row?
if ($this->HasHeaderRow)
if ($CurrentRow < 1) continue;
// are there any rows to ignore?
if (in_array($CurrentRow, $this->RowsToIgnore))
continue;
// line 45
$Classes[$Data[$GroupColumn]][] = array_filter($Data, function ($var) use ($GroupColumn, $Data) {
return $var !== $Data[$GroupColumn];
});
}
return $Classes;
}
public function __destruct() {
fclose($this->FileHandle);
}
}
// usage
$csv = new CSVParser("mycsv.csv");
$csv->hasHeaderRow(true);
$classes = $csv->groupByColumn(0));
</code></pre>
<p>I'm a little unsure about the removal of the group by column from the array entries on <code>line 45</code>.</p>
<p>Can anyone see a better method of achieving this?</p>
|
[] |
[
{
"body": "<p>Ok, before I set of, there are 3 things to keep in mind here: Code review has to be tough, to be good, so if this hurts your feelings - sorry, but I'm trying to help.<br>\nThe second thing is: Please, please, please try to adhere to the coding standards as defined by PHP-FIG (google them). Most, if not all, major players adhere to them, and you should, too. Sure, they're not official (yet), but there are no official standards... the more people adhere to a given set of unofficial rules, the more likely it is they become standard.<br>\nAnd finally: Please, document your code... you add some comments here and there, but not nearly as much as required... the main method of your class will bite you in the bum if you leave it be for a couple of months, and then decide to add something or debug it a little...</p>\n\n<p>Now, to business. As I usually do, I'll be going through your code bit by bit, suggesting and commenting along the way</p>\n\n<pre><code>class CSVParser\n{//next line, PHP-FIG style\n\n /**\n * @var string\n **/\n protected $fileName = null;//camelCase plz\n /**\n * @var resource <file handle>\n **/\n protected $fileHandle = null;\n /**\n * @var bool\n **/\n protected $hasHeaderRow = false;\n /**\n * @var array<mixed>\n **/\n protected $rowsToIgnore = array();\n</code></pre>\n\n<p>Now, I'd initialize the properties to <code>null</code>, simply because it's a good habit if you're ever in the situation where you find yourself switching from one language to another.<br>\nI'd also add doc-blocks per property to <em>document</em> what types these properties will be assigned<br>\nI'd also strongly suggest defining the properties as <em>protected</em>, since a class that reads files should be quite generic, and easy to extend from. If you extend, therefore, <code>private</code> is not always very useful...</p>\n\n<p>Now, the methods:</p>\n\n<pre><code>public function __construct ($FileName, $Mode = \"r\")\n{\n $this->FileName = $FileName;\n if (($this->FileHandle = fopen($this->FileName, $Mode)) === FALSE)\n return false;///????\n}\n</code></pre>\n\n<p>This one is a big problem: At no point are you <em>checking the type</em> of any of the arguments that you're receiving. Is <code>$FileName</code> even a string? is it <code>null</code>?<br>\nWorse still: <code>$Mode</code> is the mode in which you want to open the file... fine, there's a limited amount of <em>valid</em> strings that can be passed here. For the ease of the user, and to improve readability of the code that uses your class, I'd create <em>constants</em> for the <code>$Mode</code> parameter.<br>\nThen: <code>return false</code>? Seriously? From a constructor? A constructor returns an instance of the given class. All other <code>return</code> statements are pointless, they are ignored. If this were to work, this requires the user to write code like this:</p>\n\n<pre><code>$reader = new CSVParser($file, 'r');\nif ($reader === false)\n{\n //handle error\n}\n</code></pre>\n\n<p>Which is just messy. If you must, throw an exception, but better yet: allow the user to set the file that needs to be read later on. That way, the user can create the instance, and <em>re-use it</em> throughout his code. Here's what I'd write:</p>\n\n<pre><code>const OPEN_READ = 'r';\nconst OPEN_WRITE = 'w';\nconst OPEN_APPEND = 'a';\nconst OPEN_BIN_READ = 'rb';\nconst OPEN_BIN_WRITE = 'wb';\n//and so on\npublic function __construct($file = null, $mode = self::OPEN_READ)\n{\n if ($file)\n {\n if (is_string($file))\n {\n $this->fileName = $file;\n if (!($this->fileHandle = fopen($file, $mode))\n throw new RuntimeException('Opening file '.$file.' failed');\n return $this;//success\n }\n throw new InvalidArgumentException('File argument is not a string');\n }\n //nothing passed => just fine...\n}\n</code></pre>\n\n<p>But this is far from perfect: you <em>should</em> provide support for the <code>SplFileInfo</code> class (users passing an instance of <code>SplFileInfo</code> should work, too) and perhaps allow them to pass a file handle <em>they</em> opened already.<br>\nWhat you've also failed to do is allow the user to set the <code>hasHeaderRow</code> in the constructor. Now, I'm no big fan of constructors requiring too many arguments, so what I'd probably write is something like:</p>\n\n<pre><code>public function __construct($mixed)\n{\n if ($mixed instanceof SplFileInfo) return $this->openSplFile($mixed);\n if (is_resource($mixed)) return $this->useFileHandle($mixed);\n //is string, array, some other instance...\n}\n</code></pre>\n\n<p>But that's what I would do, not what you <em>must</em> do.<br>\nOnwards:</p>\n\n<pre><code>public function hasHeaderRow ($flag = false)\n{\n $this->hasHeaderRow = (bool) $flag;\n return $this;\n}\n\npublic function ignoreRows (array $Rows)\n{\n $this->rowsToIgnore = $Rows;\n return $this;\n}\n</code></pre>\n\n<p>I've added the <code>return $this;</code> statements simply because I like chainable API's. Now the user can write:</p>\n\n<pre><code>$instance->hasHeaderRow(true)\n ->ignoreRows($someArray);\n</code></pre>\n\n<p>Other than that, the <code>hasHeaderRow</code> is fine, but the <code>ignoreRows</code> method is, to my eye a tad vague, and I don't like how it doesn't allow me to <em>merge in</em> new rows to the ignore array. Perhaps consider writing</p>\n\n<pre><code>public function ignoreRows(array $rows, $merge = false)\n{\n if ($merge){\n $this->rowsToIgnore = array_merge(\n $this->rowsToIgnore,\n $rows\n );\n return $this;\n }\n $this->rowsToIgnore = $rows;\n return $this;\n}\n</code></pre>\n\n<p>Now, I'll skip the <code>groupByColumn</code> method for now, because there's a lot of things I to review there, so first, let's look at this:</p>\n\n<pre><code>public function __destruct()\n{\n fclose($this->fileHandle);\n}\n</code></pre>\n\n<p>Nice, that's a sensible use of the constructor method. But what about any of the <em>other</em> magic methods? <code>__sleep</code> and <code>__clone</code> to name just 2? All those methods, if a file-handle is concerned should probably be implemented to close the file, or (<code>__clone</code> for example) should return false, or throw an exception.<br>\nI've also hinted at this in the beginning of this answer: what if I were to write some app that had to parse several files? Using your class, I'd have to create a new instance for each file. That's just adding pointless overhead. I'd propose you add a <code>openFile</code> method, that works similarly to the constructor (ideally accepting <code>SplFileInfo</code> and the like, too). This <code>openFile</code> method, then could look like this:</p>\n\n<pre><code>public function openFile($mixed)\n{\n if ($this->fileHandle !== null && is_resource($this->fileHandle))\n {\n $this->fileName = null; //<<this is never used throughout your code!\n fclose($this->fileHandle);\n //and so on, re-initialize all properties\n }\n //add same if's and else's as in __constructor here\n return $this;\n}\n</code></pre>\n\n<p>Now, I'll post this answer because it's gotten quite lengthy already. Meanwhile, I'll examing the <code>groupByColumn</code> method to actually get to grips with it... it's short, sure, but would you be able to maintain it 6 months from now? If yes: right... ;-P</p>\n\n<hr>\n\n<p>Now the main function... not only is it a nightmare to read, it again fails to validate any of the params it received, and it contains <em>bugs!</em><br>\nA line by line once-over:</p>\n\n<pre><code>public function groupByColumn ($groupColumn = 0, $rowLength = 1000, $seperator = \",\")\n{\n $currentRow = -1;//why, you don't need this\n $classes = array();//what do you mean \"classes\"\n while ($data = fgetcsv($this->fileHandle, $rowLength, $seperator))\n {//no need for the !== false\n $currentRow++;//\n if ($this->hasHeaderRow)//Why check this on each iteration?\n if ($currentRow < 1) continue;//ouch continue\n if (in_array($currentRow, $this->RowsToIgnore))\n continue;//ouch again\n //maintain this... good luck\n $classes[$data[$groupColumn]][] = array_filter(//should issue notice\n $data,\n function ($var) use ($groupColumn, $data)\n {//think Gloves (you're over-complicating)\n return $var !== $data[$groupColumn];\n }\n );\n }\n return $classes;\n}\n</code></pre>\n\n<p>Now without too many words, I'll just re-write the same code to do what -I think- it is you're trying to acchieve</p>\n\n<pre><code>public function groupByColumn ($groupColumn = 0, $rowLength = 1000, $seperator = \",\")\n{\n $lines = array();\n if ($this->hasHeaderRow)\n fgetcsv($this->fileHandle,\n $rowLength,\n $separator);\n $count = 0;\n while ($data = fgetcsv($this->fileHandle, $rowLength, $seperator))\n {\n if (!in_array(++$count, $this->rowsToIgnore))\n {\n $idx = $data[$groupByColumn];\n unset($data[$groupByColumn]);\n if (!isset($lines[$idx])) $lines[$idx] = array();\n $lines[$idx][] = $data;\n }\n }\n return $lines;\n}\n</code></pre>\n\n<p>Now not only is this code smaller, it's safer, it is also not producing notices, less resource hungry, and it is, IMO, a lot easier to read. It's not difficult to understand the code, but let me back my claims up:</p>\n\n<ul>\n<li>safer: your <code>array_filter</code> was removing duplicate <em>Values</em> but if I were to group by a <em>\"column\"</em> that contained a number, and my data looked like this: <code>123,4364, foobar,123</code>, I could be removing 2 values from the array. You only need to remove 1: the value associated with the group-by column, of which you <em>have the offset</em>. Using <code>unset</code> is faster, and safer</li>\n<li>No notices: well, for each new <code>$data[$groupByColumn]</code> value, you need to create a new array. You never do so explicitly. <code>$classes[$data[$groupByColumn]][]</code><-- the latter just <em>assumes</em> there is an array. If it doesn't exist, PHP will create one for you, but it will produce a notice, too, which slows you down.</li>\n<li>less resources required: simply because I'm calling less functions and not using a lambda function (which, in PHP is an instance of the <code>Closure</code> class anyway). You create an instance on each iteration... calling a constructor each time... I use <code>unset</code> + the index of an array, which is a simple <code>HashTable</code> lookup internally.<Br>\nSure, PHP will probably optimize this, and create a single instance of <code>Closure</code> but this instance <em>will</em> be GC'ed once this method returns. So you're still creating instances each time this method gets called.</li>\n</ul>\n\n<p>Well, that's my review, hope you find a thing or 2 useful in this verbal diarrhea. I've written this all in one go, off the top of my head, and I didn't check any code I posted here, so there might be some syntax errors (and grammar errors) in here, but hey... </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:46:44.977",
"Id": "66118",
"Score": "0",
"body": "Firstly, thanks for taking the time to answer. Maybe I should have pointed out that this was just a helper class to tidy up a problem being solved procedurally, hence the poor standard. Everything you have pointed out are things I would slate colleagues for as well but I will definitely bear everything in mind when posting code sample to Code review. Secondly, I am unsure what the purpose of the statement after the `if ($this->hasHeaderRow)` condition. Your method would make sense if `hadHeaderRow` was pushed into `rowsToIgnore` as the purpose of the property is to Ignore the first row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:54:45.477",
"Id": "66122",
"Score": "0",
"body": "@IanBrindley: Well, before the actual loop starts, and `$this->hasHeaderRow` is true, I already call `fgetcsv` once, so the first row is ignored no matter what. There's no need to push anything to `$this->rowsToIgnore`, simply because the header was read before the actual data-processing began: the header never makes it to the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:04:47.510",
"Id": "66123",
"Score": "0",
"body": "I'm with you now. Personally I would refactor this and completely remove that statement by pushing `$this->hasHeaderRow` (0) to `$this->rowsToIgnore`. I don't feel that it will impact readability if the class followed commenting conventions. Also, in the working copy of this class I had made a note of simply using `unset` on `$data[$groupByColumn]`. Would I be correct in saying that `array_values` would need to be called on `$lines[$idx][] = $data;` to reset the array keys thus removing any issues in using the returned `$lines`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:33:59.313",
"Id": "66133",
"Score": "0",
"body": "@IanBrindley: calling `array_values` would reset the keys, yes... would that really be an issue, though? If so, though I could be wrong here, I think that -generally- `sort()` is a faster way to reset the keys, but if the order matters, too, also check `explode('!@$#$', implode('!@$#$', $data));` or some other wacky delimiter..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:07:25.353",
"Id": "39474",
"ParentId": "39457",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39474",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T10:42:41.330",
"Id": "39457",
"Score": "2",
"Tags": [
"php",
"array",
"csv"
],
"Title": "Grouping a CSV by column"
}
|
39457
|
<p>I began the journey to be a self-taught programmer about a month ago and my biggest fear about teaching myself is developing bad habits and not realizing it.</p>
<p>I'm looking for criticism on this "Guess a Number" game. It's my first real "project" that I've invested serious time into so I feel like this is my first opportunity to be critiqued.</p>
<pre><code>package guessANumber;
import java.util.Random;
import javax.swing.JOptionPane;
/**
* @author Mike Medina
*/
/**
* The "Guess a Number" game
* */
public class Guess {
static boolean playAgain;
static int max; // The objective will be between 1 and this number
static int objective; // Users are trying to guess this number
static int userGuess;
public Guess() {}
/**
* Runs the game while playAgain == true
*/
public static void main(String[] args) {
do {
setMax();
setObjective();
userGuess();
playAgain();
} while (playAgain == true);
}
/**
* Asks the user to set the max value they will guess between and validates it
*/
public static void setMax() {
boolean valid = false;
// Asks user for "max"
while(!valid) {
try {
max = Integer.parseInt(JOptionPane.showInputDialog("You will try to guess a number between 1 and \"max\". Set max: "));
valid = true;
}
catch (NumberFormatException e) {}
}
// Ensures user input for max is greater than 1 and fits in an int
while (max < 1 || max > Integer.MAX_VALUE) {
valid = false;
while (!valid) {
try {
max = Integer.parseInt(JOptionPane.showInputDialog("Max must be between 1 and " + Integer.MAX_VALUE + ": "));
valid = true;
}
catch(NumberFormatException e) {}
}
}
}
/**
* Sets the objective between 1 and "max"
*/
public static void setObjective() {
Random rand = new Random();
if (max == 1)
objective = 1;
else
objective = rand.nextInt(max - 1) + 1;
// Prints objective for testing
System.out.println(objective);
}
/**
* Takes in the user's guess, validates it, and tells them when they win
*/
public static void userGuess() {
// Prompts user for guess and ensures it's an integer
do {
userGuess = 0;
try {
userGuess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and " + max + ": "));
}
catch (NumberFormatException e){}
// Ensures user's guess is an integer greater than 0 and less than max
while (userGuess > max || userGuess < 1) {
try {
userGuess = Integer.parseInt(JOptionPane.showInputDialog(null, "Your guess must be between 1 and " + max));
}
catch (NumberFormatException e) {}
}
userWinLose();
} while (userGuess != objective);
}
/**
* Tells the user whether their guess was high, low, or correct
*/
public static void userWinLose() {
// Tells the user their guess was too high, too low, or correct
if (userGuess < objective)
JOptionPane.showMessageDialog(null, "Too low!");
else if (userGuess > objective)
JOptionPane.showMessageDialog(null, "Too high!");
else
JOptionPane.showMessageDialog(null, "You win!");
}
/**
* Asks the user if they want to play again or quit
*/
public static void playAgain() {
boolean valid = false;
// Confirms user input is an integer
while (!valid) {
try {
if (Integer.parseInt(JOptionPane.showInputDialog("Enter 0 to quit or 1 to play again: ")) == 0)
playAgain = false;
else
playAgain = true;
valid = true;
}
catch (NumberFormatException e) {}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:30:50.590",
"Id": "66215",
"Score": "2",
"body": "I like the humility with which you are approaching programming. You'll learn faster than, and be easier to get along with, me when I started out."
}
] |
[
{
"body": "<p>Overall it looks pretty good. A few pointers though...</p>\n\n<ul>\n<li><p>Try to indent your code properly. Most of it looks good but on a few places you have missed an indentation. e.g.,</p>\n\n<pre><code>do {\nsetMax();\nsetObjective();\nuserGuess();\nplayAgain();\n} while (playAgain == true);\n</code></pre></li>\n<li><p>Don't consume nor fail silently on exceptions (except in some rare cases but that's out of scope here)</p>\n\n<pre><code>catch (NumberFormatException e) {} // don't do this\n</code></pre></li>\n<li><p>Surround your statements with appropriate curly brackets</p>\n\n<pre><code>if (max == 1) // no brackets!\n objective = 1;\nelse // no brackets!\n objective = rand.nextInt(max - 1) + 1;\n</code></pre></li>\n</ul>\n\n<p>Some people don't do it out of habbit, or coding style, etc. It may not be a problem but as your codebase expands it could become a problem and IIRC Java style docs advice against omitting curly brackets. Here's an example of why it may be a bad idea <a href=\"https://stackoverflow.com/a/8020255/1021726\">https://stackoverflow.com/a/8020255/1021726</a></p>\n\n<ul>\n<li><code>max > Integer.MAX_VALUE</code> Will never happen</li>\n</ul>\n\n<p>Because <code>max</code> is declared as an integer and assigned the value entered in the JOptionPane. In the event of an user would enter a value which is higher than <code>Integer.MAX_VALUE</code> it would throw an exception. And since you do not do anything with your exceptions it will just fail silently. See point #2.</p>\n\n<ul>\n<li>static vs non-static</li>\n</ul>\n\n<p>Do you understand <code>static</code>? If not, then you can get a quick brief here <a href=\"http://www.caveofprogramming.com/frontpage/articles/java/java-for-beginners-static-variables-what-are-they/\" rel=\"nofollow noreferrer\">http://www.caveofprogramming.com/frontpage/articles/java/java-for-beginners-static-variables-what-are-they/</a></p>\n\n<p>If you understand static, you may realize that you do not want two instances of your <code>Guess</code> class to share the same variable.</p>\n\n<ul>\n<li><p>Declare the access modifier</p>\n\n<pre><code>static boolean playAgain; // no access modifier\n</code></pre></li>\n</ul>\n\n<p>While your variables lack <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html\" rel=\"nofollow noreferrer\">access modifiers</a> (and I do not think it's by purpose), and it may not be a problem as then it defaults as <em>package-private</em>, but you need to beware that it's important to design your class, it's members and variables accordingly to how they should be used. Are your variables really <em>package-private</em>, or should they rather be declared as just <code>private</code> variables?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:03:42.987",
"Id": "66088",
"Score": "0",
"body": "2. I was using try-catch in a loop to get the right input without showing an error. Is there a more graceful way to do this without abusing try-catch? 3. Hmm I thought it was good practice to avoid \"excess\" brackets if the if statement was one line but I understand how that could complicate things. Noted! 4. I thought if they entered a value higher than an int can hold, it would wrap around to negative. Also noted! 5. I guess this is part of OOP I don't understand yet. When would I ever use more than one instance of guess? 6. LoudandClear!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:18:33.120",
"Id": "66089",
"Score": "1",
"body": "2. You could display a JOptionPane explaining that the user entered a number in the wrong range. This borders into the scope of good UI/UX, as now the user will now why his input failed. And what do you mean by abusing try/catch? 4. If you increment a value past `Integer.MAX_VALUE` then yes, but you cant assign an int a value higher than *2147483647*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:37:05.533",
"Id": "66115",
"Score": "0",
"body": "I guess I didn't understand the brackets of catch were for displaying an error message. Still a beginner! and 4. makes perfect sense. Thanks again! Do you have any example of a scenario when I would have more than one instance of guess? Like I said, I'm still sort of struggling with the implementation of the \"object\" part of object oriented programming ^^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:36:20.183",
"Id": "66134",
"Score": "1",
"body": "Well, they're not for displaying an error message, they are for handling an exceptional case that might occur when running the code. One of the many ways of handling exception cases includes logging the error message and displaying an error message to the user. 4. Imagine JRE is a casino and `Guess` is slot machines. If you would put a lot of slot machines in your casino and they all shared static variables, each slot machine would share the same state, same display, same output and have the same amount of money put into them. Now switch out slot machines into Guess instances and there you go."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:44:17.483",
"Id": "66143",
"Score": "0",
"body": "So if I need to access a variable in multiple different methods all in the same class, do I set the variable as private static? Or is there a way to avoid using static and still access one variable throughout the class?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:36:52.793",
"Id": "39461",
"ParentId": "39459",
"Score": "17"
}
},
{
"body": "<p>On top of the comments already given :</p>\n\n<p>Keep things simple :</p>\n\n<ul>\n<li><code>while (playAgain == true)</code> can be written <code>while (playAgain)</code></li>\n<li><code>if (A) variable=false; else variable=true;</code> can be written <code>variable = !A;</code></li>\n<li>Do not repeat yourself : if you deal a lot with user input and checking values, make it a function you can reuse.</li>\n<li>You do not need static members. Local variable can do the trick. The idea is to keep things in the smallest possible scope so that it's easier to understand what changes what.</li>\n</ul>\n\n<p>Here's my code taking into account my comments :</p>\n\n<pre><code>import java.util.Random;\nimport javax.swing.JOptionPane;\n\n/**\n * The \"Guess a Number\" game\n * */\npublic class Guess {\n public Guess() {}\n\n /**\n * Runs the game while playAgain == true\n */ \n public static void main(String[] args) {\n do {\n int max = getMax();\n int obj = getObjective();\n userGuess(obj, max);\n } while (playAgain());\n }\n\n private static int getIntFromUser(String text, int min, int max)\n {\n while (true)\n {\n try\n {\n int val = Integer.parseInt(JOptionPane.showInputDialog(text));\n if (min <= val && val <= max)\n return val;\n }\n catch (NumberFormatException e) { /* As pointed out by ChrisW, it might be worth having something here */}\n }\n }\n\n /**\n * Asks the user for the max value\n */\n public static void getMax() {\n return getIntFromUser(\"You will try to guess a number between 1 and \\\"max\\\". Set max: \", 1, Integer.MAX_VALUE);\n }\n\n /**\n * Gets the objective between 1 and \"max\"\n */\n public static int getObjective() {\n // Please read Simon André Forsberg's comment about this.\n Random rand = new Random();\n return (max == 1) ?\n 1 :\n rand.nextInt(max - 1) + 1;\n }\n\n /**\n * Takes in the user's guess, validates it, and tells them when they win\n */\n public static void userGuess(int obj, int max) {\n int userGuess;\n do {\n userGuess = getIntFromUser(\"Guess a number between 1 and \" + max + \": \", 1, max);\n userWinLose(userGuess, obj);\n } while (userGuess != obj);\n }\n\n /**\n * Tells the user whether their guess was high, low, or correct\n */\n public static void userWinLose(int guess, int objective) {\n if (guess < objective)\n JOptionPane.showMessageDialog(null, \"Too low!\");\n else if (guess > objective)\n JOptionPane.showMessageDialog(null, \"Too high!\");\n else\n JOptionPane.showMessageDialog(null, \"You win!\");\n }\n\n /**\n * Asks the user if they want to play again or quit\n */\n public static boolean playAgain() {\n return (getIntFromUser(\"Enter 0 to quit or 1 to play again\", 0, 1) == 1);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:04:19.727",
"Id": "66099",
"Score": "4",
"body": "+1 but it worries me to see a silently-ignored exception. @MikeMedina Maybe use that to add an error message displayed to the user: `String errorMessage; try { ....showInputDialog(errorMessage + text); ...; } catch (NumberFormatException e) { errorMessage = \"That was not a number! Please try again.\\n\\n\"; }` or something like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:51:16.197",
"Id": "66105",
"Score": "0",
"body": "Ok, I had a big mess of tangled while loops before I learned what try-catch was through some googling. I guess I started using it without fully understanding it but this makes sense!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:25:01.950",
"Id": "66126",
"Score": "0",
"body": "One though, that playAgain = playAgain() kind of irks me.\n\nMaybe just while(playAgain()), you are not using that variable elsewhere. Failing that maybe a rename?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:26:24.930",
"Id": "66128",
"Score": "0",
"body": "@apieceoffruit You're right on this. The `while (playAgain());` from rolfl'answer is much better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:30:13.113",
"Id": "66131",
"Score": "0",
"body": "You use the [ternary operator](http://en.wikipedia.org/wiki/%3F:) but don't explain it anywhere. I feel like this can be confusing for someone who has never seen it before. Also `public static void getObjective()` looks to return an int..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:38:24.687",
"Id": "66137",
"Score": "0",
"body": "imho you want `int` in your `userGuess` variable definition, and `guess` instead of `userGuess` in your `userWinLose` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:43:52.520",
"Id": "66141",
"Score": "0",
"body": "@Danny : Indeed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:44:10.740",
"Id": "66142",
"Score": "0",
"body": "@ChrisW : Indeed, I've fixed this! Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:42:35.683",
"Id": "66150",
"Score": "1",
"body": "`public static void getObjective()` should return an `int` I believe :) And should also be written as `return rand.nextInt(max) + 1;` to generate from 1 to max inclusive. And `Random` objects are meant to be **re-used**!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:51:18.583",
"Id": "66153",
"Score": "0",
"body": "@SimonAndréForsberg Thanks for spotting this. I've updated my answer to reflect your comment. As I don't know much about the Java Random interface, I've just added a pointer to your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:09:06.417",
"Id": "66191",
"Score": "0",
"body": "@Josay This doesn't have much to do with Java per se. Random number generators do (possibly contrary to intuition) carry state and are seeded, so they must be reused. It's the same for C++, C#, Java, etc. I've taken the liberty to move `rand` outside of the function. I hope that's fine with you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T17:38:53.390",
"Id": "66307",
"Score": "0",
"body": "@Josay Apparently, my edit was rejected. You'll have to move `rand` out yourself I think."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:08:52.667",
"Id": "39463",
"ParentId": "39459",
"Score": "26"
}
},
{
"body": "<p>Both Josay and Max have given great answers. There are two things I would like to add.</p>\n\n<ol>\n<li><p>There is no need to carry the <code>playagain</code> boolean variable. You can simply:</p>\n\n<pre><code>do {\n ....\n} while (playAgain());\n</code></pre></li>\n<li><p>There is a bug in your <code>getObjective()</code> method. You will never generate the 'max' value itself (unless it is 1). From the Java API <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29\" rel=\"nofollow noreferrer\">Documentation for nextInt(n)</a>: </p>\n\n<blockquote>\n <p>Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)`</p>\n</blockquote>\n\n<p>... so you ask the user to enter a <code>max</code>, lets say, for example, they enter <code>5</code>. Now, your getObjectiveMethod does <code>rand.nextInt(max - 1) + 1;</code> which will generate a random number from <code>0</code> through <code>(5-1)</code>, which, since <code>(5 - 1)</code> is 4, and the random value will be <strong>exclusive</strong> of 4, the largest random number generated will be <code>3</code>. Add <code>1</code> to this again, and you get 4. Thus, your largest Objective will never be <code>5</code>, or the max value.</p></li>\n</ol>\n\n<p>This Random Number generation is a common problem to encounter. There are a number of posts and blogs about this, but the logical pointer to direct you to is this StackOverflow answer: <a href=\"https://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java\">Generating Random numbers in a range</a></p>\n\n<p>The bottom line is that you want your number generated as:</p>\n\n<pre><code>rand.nextInt(max) + 1;\n</code></pre>\n\n<p>As a consequence of this, there is no need to have a special case for <code>max == 1</code>. You only need to ensure that <code>max > 0</code> when it is entered (which you should do before setting <code>valid = true</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:54:16.380",
"Id": "66106",
"Score": "0",
"body": "Thanks! I could have sworn I tested max at 3 a bunch of times to make sure I could get 3 etc. but I guess not. I read the documentation for rand but must have missed the upper bound as exclusive. Thanks for pointing this out!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:46:17.250",
"Id": "39466",
"ParentId": "39459",
"Score": "10"
}
},
{
"body": "<p>One thing you should know about exceptions is that you don't need to catch them immediately.</p>\n\n<p>The reason why code throws an exception in the exception in the first place is that it doesn't know how to handle the exception.</p>\n\n<p>Similarly, the one-higher subroutine (for example, your getIntFromUser method) which immediately called that code might also not know how to handle the exception.</p>\n\n<p>It's fine, perhaps normal, to catch the exception in a different routine much higher up the call stack.</p>\n\n<p>For example, here's a modified version of Josay's answer:</p>\n\n<pre><code>private static int getIntFromUser(String text, int min, int max)\n{\n // parseInt might throw NumberFormatException\n int val = Integer.parseInt(JOptionPane.showInputDialog(text));\n if (min <= val && val <= max)\n return val;\n else\n throw new IllegalArgumentException(\"Not an integer between \" + min + \" and \" max);\n}\n\n// display error message from caught exception\n// return true if the user wants to play again\nprivate static bool getIsContinueAfterError(String errorMessage)\n{\n String message = errorMessage + \"\\n\\nDo you want to continue playing?\";\n int reply = JOptionPane.showConfirmDialog(null, message, \"Error\", JOptionPane.YES_NO_OPTION);\n return (reply == JOptionPane.YES_OPTION);\n}\n\npublic static void main(String[] args) {\n boolean playAgain;\n do {\n try {\n int max = getMax();\n int obj = getObjective();\n userGuess(obj, max);\n playAgain = playAgain();\n }\n catch (NumberFormatException ex)\n {\n playAgain = getIsContinueAfterError(\"This is not an integer.\");\n }\n catch (IllegalArgumentException ex)\n {\n playAgain = getIsContinueAfterError(ex.getMessage());\n }\n } while (playAgain);\n}\n</code></pre>\n\n<p>This isn't necessarily a good example (in your example, you can catch and retry inside getIntFromUser); I meant it as an illustration because <a href=\"https://codereview.stackexchange.com/questions/39459/trying-to-avoid-developing-bad-habits-early-on/39478#comment66105_39463\">you said</a> that you're not familiar with exceptions.</p>\n\n<p>With your code, perhaps the user didn't enter an integer because all the number keys are broken on their keyboard; your code would catch and retry forever, whereas my code gives the user an opportunity to stop playing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:53:33.223",
"Id": "66121",
"Score": "1",
"body": "(I'm inexperienced with Java and JOptionPane so there may be syntax errors in the code above.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:26:17.063",
"Id": "66127",
"Score": "1",
"body": "Thanks for your input! I thought I was finished with the features of the program before I posted it for review but now I realize that the \"cancel\" button in the JOptionPanes doesn't work because the loop just restarts. Definitely an issue not allowing users to exit the program safely!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:52:07.623",
"Id": "39478",
"ParentId": "39459",
"Score": "5"
}
},
{
"body": "<p>with the <code>playagain</code> boolean variable you should set it to false when you create the variable and then the loop can be a simple <code>while(playagain)</code> a lot of people prefer a <code>while</code> loop over a <code>do while</code> loop because you see what the condition is right out of the gate.</p>\n\n<p><strong>EDIT:</strong>\nnow that I read through the Code again I see why you went with the <code>do while</code> and it completely makes sense, except for the following:</p>\n\n<p>your <code>PlayAgain</code> method should return a boolean value. that being said it should be caught and passed to a variable inside your <code>Main()</code> method something like <code>keepPlaying</code> and that variable should be created inside your <code>Main()</code> method. the <code>playAgain</code> boolean value is only used in two places, <code>Main()</code> and <code>playAgain()</code>, which means that you shouldn't make it global, it is specific and should be specific in scope, it doesn't affect any of the other methods in the program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:04:06.217",
"Id": "39479",
"ParentId": "39459",
"Score": "3"
}
},
{
"body": "<p>To throw you in at the deep end it would be good to start thinking more about an object-oriented design for your classes and interfaces. Think about re-usability of your code and how can encapsulate just enough useful behaviour in a class while keeping it as general as possible.</p>\n\n<p>Let's say it becomes known that you've written a wonderful class to play this guessing game and other developers want to use it in their own code. Only one guy wants to use a different GUI, another wants to have a device make differently pitched beeps depending on whether the guess is too high or low and another wants to use the game with very young kids and always set max to 10. As it stands they can't use your code because implementation specifics appear at every level.</p>\n\n<p>Let's focus on just the operation of the game. The interface is clear: a client must be able to communicate a guess to the class, and the class needs to provide an indication of whether the guess is too high, too low, or correct. So define IGuessHandler as a guess-handling interface comprising just that, and now have a class inherit it. You can then provide precisely the same implementations as now but someone else could implement different ones.</p>\n\n<p>I think you should also extract your main into some GameRunner class and generally try to have more precise names for classes and operations. Your main loop has a playAgain method which is run when we play for the first time. It seems trivial but it's sloppy thinking. Don't have a method called playAgain, have one called play which actually plays the game. You call it again and again but keep the names as clear and descriptive as possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:09:25.810",
"Id": "66158",
"Score": "1",
"body": "This is answer is EXACTLY what I was hoping to get when I decided to post here. These OOP concepts are out of my grasp because I can't understand how to use the OOP toolset to my benefit. Thank you for giving me examples on how I should be structuring my code from the start! If you have a chance, is it possible you could explain interfaces more in depth? I've actually spent A LOT of time researching interfaces and I just can't wrap my head around the concept. It seems to me like it they're just lists of methods that \"should\" be included. What good is a list of method titles?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:09:34.440",
"Id": "66159",
"Score": "1",
"body": "However [YAGNI](http://en.wikipedia.org/wiki/You_aren't_gonna_need_it) is worth practising too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:16:51.013",
"Id": "66161",
"Score": "0",
"body": "Originally, when the came was entirely console based, I did have everything currently in my main() method included in a separate class but it felt silly to have an entirely separate class just for running the methods from the first class. I guess I just haven't had enough exposure to conventional design structure yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:25:18.070",
"Id": "66165",
"Score": "1",
"body": "Just think of an interface as specifying a set of behaviour that any class implementing the interface must provide. Thinking about my previous answer I'd now change it a bit. There's no one right way to do this, but let's define IGuessHandler as an interface which has a handleGuess(int) method which returns an instance of a GuessOutcome base class. This can be characterised as having an internal state of TOO_LOW, TOO_HIGH, CORRECT (defined as enums) and a Render() method. You can then derive your own class from this with the same implementation as before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:41:00.360",
"Id": "66181",
"Score": "1",
"body": "@MikeMedina It's tempting to over-complicate a design. Instead I'd suggest keeping it as simple as possible (without interfaces) until you need them. If you need them in future then you can get them by [refactoring](https://www.google.com/search?q=refactoring+extract+interface). The simpler it is now, the sooner it's written and the easier it is to refactor later, if necessary, **after** you know whether you want to add new functionality, and know what that functionality is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:28:53.033",
"Id": "66200",
"Score": "0",
"body": "Solid advice @ChrisW the \"YAGNI\" thought process seems pretty logical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:29:24.567",
"Id": "66201",
"Score": "0",
"body": "@TheMathemagician I can understand that an interface forces the class to implement the included methods, but if the person using the class has to implement those methods themselves anyway, why force that restraint? If the person is going to write the methods anyway, I don't understand what purpose forcing them to be written serves x.x I've spent a lot of time trying to understand the concept and it always seems to go right over my head :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T20:33:33.177",
"Id": "66224",
"Score": "1",
"body": "@MikeMedina IMO an 'interface' separate from a class is worthwhile when you want to 'plug-in' two different classes (two different implementations, or even just two different versions of the same class). E.g. in future you might want two types of guesser: 1) users who guess interactively 2) software that guesses automatically. Then, it might be worth defining `interface IGuess { int getGuess(); }` which is implemented by `class UserGuess implements IGuess { public int getGuess() { return Integer.parseInt(JOptionPane.showInputDialog(\"What is your guess?\")); } }`. Until then, I wouldn't bother."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:43:22.013",
"Id": "66244",
"Score": "1",
"body": "@MikeMedina Splitting your code into building blocks connected via interfaces doesn't 'force a restraint' at all. It frees you from restraints. The logic which determines whether the guess was too high and how you convey the outcome back to the user have nothing to do with each other so coupling them together in one class like conjoined-twins is crippling. Your implementation displays a dialog using a particular library, but as I said before, someone else might want to make a sound, or flash a colour. Separating the internal logic from the user interface makes maintenance easier too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:22:10.510",
"Id": "80743",
"Score": "0",
"body": "@MikeMedina: an object is 2 things: internals, and an interface. \"the rest of the world\" NEEDS to use ONLY the interface to access the object (get/setvalueof, fonction1, etc). The internals needs to be out of (direct) reach. Doing this allow you to fix/change the internals as you wish/need, without having to change anything in everything of \"the outside world\" : they use the same interface, and won't even know the internals changed. (Of course, at first, you sit down and write the BEST possible interface! That part should never change, except add new things without breaking the previous ones)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:41:23.390",
"Id": "39482",
"ParentId": "39459",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "39463",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T11:19:22.910",
"Id": "39459",
"Score": "30",
"Tags": [
"java",
"beginner",
"game",
"formatting",
"number-guessing-game"
],
"Title": "\"Guess a number\" game"
}
|
39459
|
<p>I am setting different <code>RadioGroup</code> like this:</p>
<pre><code>fragment.setT1RadioGroup((RadioGroup)fragView.findViewById(rowids[0]).findViewById(R.id.t1_radiogroup));
fragment.setT2RadioGroup((RadioGroup)fragView.findViewById(rowids[1]).findViewById(R.id.t1_radiogroup));
fragment.setT3RadioGroup((RadioGroup)fragView.findViewById(rowids[2]).findViewById(R.id.t1_radiogroup));
fragment.setT4RadioGroup((RadioGroup)fragView.findViewById(rowids[3]).findViewById(R.id.t1_radiogroup));
fragment.setT5RadioGroup((RadioGroup)fragView.findViewById(rowids[4]).findViewById(R.id.t1_radiogroup));
fragment.setT6RadioGroup((RadioGroup)fragView.findViewById(rowids[5]).findViewById(R.id.t1_radiogroup));
fragment.setT7RadioGroup((RadioGroup)fragView.findViewById(rowids[6]).findViewById(R.id.t1_radiogroup));
fragment.setT8RadioGroup((RadioGroup)fragView.findViewById(rowids[7]).findViewById(R.id.t1_radiogroup));
fragment.setT9RadioGroup((RadioGroup)fragView.findViewById(rowids[8]).findViewById(R.id.t1_radiogroup));
fragment.setT10RadioGroup((RadioGroup)fragView.findViewById(rowids[9]).findViewById(R.id.t1_radiogroup));
</code></pre>
<p>For refactoring purpose could I reduce the size of this code? How?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:03:16.707",
"Id": "66098",
"Score": "0",
"body": "Show us your code for whatever the `fragment` object is. In what way is the `fragment.setT1RadioGroup` different from `fragment.setT2RadioGroup`?"
}
] |
[
{
"body": "<p>Assuming that <code>setT5RadioGroup</code> only sets a variable within the fragment:</p>\n\n<p>In your fragment, use <code>RadioGroup[] radioGroups = new RadioGroup[10];</code></p>\n\n<pre><code>setTRadioGroup(int number, RadioGroup grp) {\n this.radioGroups[number] = grp;\n}\n</code></pre>\n\n<p>In your activity, or whatever it is:</p>\n\n<pre><code>for (int i = 0; i < rowids.length; i++) { // assuming rowids.length is 10\n RadioGroup grp = (RadioGroup)fragView.findViewById(rowids[i]).findViewById(R.id.t1_radiogroup);\n fragment.setTRadioGroup(i, grp);\n}\n</code></pre>\n\n<p>Whenever you find yourself using multiple numbered methods that does very similar things, think: <strong>Array!!</strong> (or possibly <code>List<ElementType></code> if you want to be able to add/remove dynamically)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:10:12.853",
"Id": "39469",
"ParentId": "39468",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39469",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T12:58:13.627",
"Id": "39468",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Refactoring RadioGroup setter code?"
}
|
39468
|
<p>I've implemented just as Ryan Bates suggested in his <a href="http://railscasts.com/episodes/217-multistep-forms" rel="nofollow">railscast episode</a>, I've got everything working just right, so here is his approach in the controller :</p>
<pre><code>def new
session[:order_params] ||= {}
@order = Order.new(session[:order_params])
@order.current_step = session[:order_step]
end
def create
session[:order_params].deep_merge!(params[:order]) if params[:order]
@order = Order.new(session[:order_params])
@order.current_step = session[:order_step]
if @order.valid?
if params[:back_button]
@order.previous_step
elsif @order.last_step?
@order.save if @order.all_valid?
else
@order.next_step
end
session[:order_step] = @order.current_step
end
if @order.new_record?
render "new"
else
session[:order_step] = session[:order_params] = nil
flash[:notice] = "Order saved!"
redirect_to @order
end
end
</code></pre>
<p>I'm ok with new method, but I wonder how can the create method be refactored. He said that he will do an episode how to refactor this in the future but he did not yet.</p>
<p>This was my take on he reactoring (more splitting than refactoring):</p>
<pre><code> def create
session[:order_params].deep_merge!(params[:order]) if params[:order]
@order = Order.new(session[:order_params])
@order.current_step = session[:order_step]
process_step
if @order.new_record?
render "new"
else
session[:order_step] = session[:order_params] = nil
flash[:notice] = "Order saved!"
redirect_to @order
end
end
def process_step
if @order.valid?
if params[:back_button]
@order.previous_step
elsif @order.last_step?
@order.save if @order.all_valid?
else
@order.next_step
end
session[:order_step] = @order.current_step
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T20:40:30.010",
"Id": "74116",
"Score": "0",
"body": "If you found @BroiSatse's answer helpful, please checkmark it."
}
] |
[
{
"body": "<p>I would advise you to look at wicked gem: <a href=\"https://github.com/schneems/wicked\">https://github.com/schneems/wicked</a>.</p>\n\n<p>Using this gem you could write:</p>\n\n<pre><code>include Wicked::Wizard\nsteps <list_of_your_steps>\n\ndef new\n session[:order_id] ||= Order.create.id\nend\n\ndef show\n @order = Order.find(session[:order_id])\nend\n\ndef update\n @order = Order.find(session[:order_id])\n @order.assign_attributes(params[:order_params])\n @order.current_step = step\n render_wizard @order\nend\n</code></pre>\n\n<p>It will also separate your forms for each step. To add any step-related action you can use <code>step</code> reader:</p>\n\n<pre><code>def update\n @order = Order.find(session[:order_id])\n @order.assign_attributes(params[:order_params])\n @order.current_step = step\n @order.do_sth if step == :my_step \n render_wizard @order\nend\n</code></pre>\n\n<p><code>render_wizard</code> automatically tries to save an object and redirects you to the next step or renders current form depending on a result. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T10:28:44.597",
"Id": "40727",
"ParentId": "39470",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:11:05.047",
"Id": "39470",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Refactoring multistep form rails"
}
|
39470
|
<p>I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.</p>
<p>If you are unfamiliar with unity3d, ignore the use of UnityEngine, the heritage from <code>MonoBehaviour</code> as well as the <code>Debug.Log();</code>, <code>Debug.LogWarning();</code>, and <code>Debug.LogError();</code>.</p>
<pre><code>using UnityEngine;
public class Party : MonoBehaviour {
private ItemSlot[] inventory;
public const int INVENTORY_SIZE = 50;
public Party () {
ItemSlot[] inventory = new ItemSlot[INVENTORY_SIZE];
}
// add q item
// returns if there was space in inventory or not
public bool AddItem (Item item, int q) {
// checks if the item already exist in inventory
// adding to its stack
for (int i = 0; i < INVENTORY_SIZE; i++) {
if (inventory[i].item == item && inventory[i].item.MaxQuantity > inventory[i].quantity) {
// if whole item fits
if (q + inventory[i].quantity <= inventory[i].item.MaxQuantity) {
Debug.Log ("Added to existing item in one stack " + q + "x " + item.Name);
inventory[i].quantity += q;
return true;
// need more slots than 1
} else {
int spotsLeft = (inventory[i].item.MaxQuantity - inventory[i].quantity);
Debug.Log("Added " + spotsLeft + "x " + item.Name + " at itemslot #" + i + " - " + q + " left.");
q -= spotsLeft;
inventory[i].quantity += spotsLeft;
// no more items to add
if (q == 0) {
Debug.Log ("Added (by stacking) " + q + "x " + item.Name);
return true;
}
}
}
}
// still have items left in stack, add to a new slot
for (int i = 0; i < INVENTORY_SIZE; i++) {
if (inventory[i].item == null) {
Debug.Log ("Added " + q + "x " + item.Name);
inventory[i] = new ItemSlot (item, q);
return true;
}
}
Debug.LogWarning ("Inventory full! " + q + "x " + item.Name + " left.");
return false;
}
public void Move (int src, int dst) {
Item tItem = inventory[dst].item;
int tQ = inventory [dst].quantity;
inventory [dst].item = inventory [src].item;
inventory [dst].quantity = inventory [src].quantity;
inventory [src].item = tItem;
inventory [src].quantity = tQ;
}
// remove q items at i
// check when calling function to make sure q is greater than or equal to ItemSlot[i].quanity
public void RemoveItem (int i, int q) {
// remove q items at i
Debug.Log ("Removed " + q + "x " + inventory[i].item.Name);
inventory [i].quantity -= q;
// removed all? delete item at i
if (inventory [i].quantity <= 0) {
Debug.Log ("Deleted " + inventory[i].item.Name);
DeleteItem (i);
}
// error, too many removed
if (inventory [i].quantity < 0) {
Debug.LogError ("Quantity at index " + i + " is " + inventory[i].quantity + "!");
inventory [i].quantity = 0;
}
}
// item at i has a q of 0, delete item
private void DeleteItem (int i) {
inventory [i].item = null;
}
}
// inventory
class ItemSlot {
public Item item;
public int quantity;
public ItemSlot (Item i, int q) {
item = i;
quantity = q;
}
}
</code></pre>
<p>Any thoughts of what I can improve? Or does it look decent?</p>
<p>I don't need a perfect answer written on a level that I don't understand. I merely want pointers of what to think about. I also welcome material to read about common mistakes.</p>
<p>My current class Item</p>
<pre><code>class item {
string _name;
int _maxQuantity;
public item () {
string _name = string.Empty;
int _maxQuantity = 0;
}
public string Name {
get {return _name;}
set {_name = value;}
}
public string MaxQuantity {
get {return _maxQuantity ;}
set {_maxQuantity = value;}
}
}
</code></pre>
<p>It will later hold more information such as description, type (consumable, weapon) and a list of modifying stats (classes storing what stat and how much the weapon increase/decrease).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:51:18.570",
"Id": "66120",
"Score": "0",
"body": "could you please provide class item as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:38:13.313",
"Id": "66136",
"Score": "0",
"body": "For now it only holds setters and getters, such as name, maxQuantity among others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:43:01.180",
"Id": "66140",
"Score": "0",
"body": "I asked because i see no reason of why quantity isn't in item... I also asked myself if maxQuantity shouldn't be in ItemSlot, but I don't know what you're trying try achieve nor your domain logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:48:25.323",
"Id": "66144",
"Score": "2",
"body": "Have you actually tried this code? It can't work, it has to throw `NullReferenceException`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:52:46.420",
"Id": "66146",
"Score": "0",
"body": "Quantity is in itemslot, it stores how many you currently have of item x. maxQuantity is the stack size of items. I dont know what domain logic is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:54:52.603",
"Id": "66147",
"Score": "0",
"body": "I have not implemented it yet. It only gives a null reference warning."
}
] |
[
{
"body": "<p>First things first. I don't see a reason for why you didn't include a quantity property in your <code>Item</code> class. Depending on this you could also treat <code>Item</code> as the same as <code>ItemSlot</code> so you could get rid of one of those classes. That being said I will review the code without that property in <code>Item</code> to be more similar to yours. I also think that you made a mistake in your Constructor. You probably would want to write:</p>\n\n<pre><code>public Party () {\n inventory = new ItemSlot[INVENTORY_SIZE];\n}\n</code></pre>\n\n<p>I also see no reason for why you shouldn't use <code>inventory.Length</code> instead of the constant so I replaced the code that makes use of that constant. Intro being made here follows the alterations that I would make:</p>\n\n<p>Move <code>Add</code> and <code>Remove</code> logic of a <code>ItemSlot</code> to your <code>ItemSlot</code> class. I did as follows:</p>\n\n<pre><code>class ItemSlot {\n public Item item;\n public int quantity;\n\n public ItemSlot (Item i, int q) {\n item = i;\n quantity = q;\n }\n\n //returns the quatity left to add\n public int Add(Item item, int q){\n if (q + quantity <= item.MaxQuantity) {\n Debug.Log (\"Added to existing item in one stack \" + q + \"x \" + item.Name);\n quantity += q;\n return 0;\n // need more slots than 1\n } else {\n int spotsLeft = item.MaxQuantity - quantity;\n Debug.Log(\"Added \" + spotsLeft + \"x \" + item.Name + \" - \" + q + \" left.\");\n q -= spotsLeft;\n quantity += spotsLeft;\n\n // no more items to add\n if (q == 0) {\n Debug.Log (\"Added (by stacking) \" + q + \"x \" + item.Name);\n return 0;\n }\n }\n return q;\n }\n\n public bool Remove(int q){\n if(quantity > q){\n quantity -= q;\n Debug.Log (\"Removed \" + q + \"x \" + item.Name)\n return true;\n }\n return false;\n }\n}\n</code></pre>\n\n<p>This change makes you have the code in the right place and results on having a \"cleaner\" <code>AddItem</code> algorithm:</p>\n\n<pre><code>private int FirstFreeSlot(){\n for(int i = 0; i < inventory.Length; ++i){\n if(inventory[i] == null)\n return i;\n }\n return -1;\n}\n\npublic bool AddItem (Item item, int q) {\n // checks if the item already exist in inventory\n // adding to its stack \n int idxFree = FirstFreeSlot();\n //you have to iterate the whole array since you can remove any position and you do not shift the elements\n for (int i = 0; i < inventory.Length; i++) {\n if (inventory[i].item == item && inventory[i].item.MaxQuantity > inventory[i].quantity) {\n int remain = inventory[i].Add(item, q);\n if(remain == 0) return true;\n if(remain > 0 && idxFree >= 0){\n Debug.Log (\"Added \" + remain + \"x \" + item.Name);\n inventory[idxFree] = new ItemSlot(item, remain);\n return true;\n }\n Debug.LogWarning (\"Inventory full! \" + q + \"x \" + item.Name + \" left.\");\n return false;\n }\n }\n //the item wasn't in inventory\n if(idxFree >= 0){\n inventory[idxFree] = new ItemSlot(item, q);\n return true;\n }\n Debug.LogWarning (\"Inventory full! \" + q + \"x \" + item.Name + \" left.\");\n return false;\n}\n</code></pre>\n\n<p>This would also imply changes to the <code>RemoveItem</code> algorithm:</p>\n\n<pre><code>public void RemoveItem (int i, int q) {\n if(!inventory[i].Remove(q)){\n Debug.LogError (\"Quantity at index \" + i + \" is \" + inventory[i].quantity + \"!\");\n inventory [i].quantity = 0;\n }\n // removed all? delete item at i\n if (inventory [i].quantity <= 0) {\n Debug.Log (\"Deleted \" + inventory[i].item.Name);\n DeleteItem (i);\n }\n\n}\n</code></pre>\n\n<p>I don't see a reason of why you don't simply swap the ItemSlots in your Move code:</p>\n\n<pre><code>public void Move (int src, int dst) {\n Itemslot aux = inventory[src];\n inventory[src] = inventory[dst];\n inventory[dst] = aux;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:15:35.353",
"Id": "66193",
"Score": "0",
"body": "The constructor has a fault yes, copy paste failed me.\n\nInventory should store 50 items instead? Why haven't I thought of that? Thank you. Looks wonderful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:23:54.043",
"Id": "66197",
"Score": "0",
"body": "the size of the array may be a number passed on the constructor for example. You are welcomed to use List<ItemSlot> instead so your inventory may increase dynamically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:27:37.283",
"Id": "66199",
"Score": "0",
"body": "It shouldn't be constant it should be the party members*50, however as I haven't really implemented party members yet I will wait with it. Will update the main post soon with my changes, I am also changing it to store Item instead of ItemSlot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:30:24.530",
"Id": "66202",
"Score": "2",
"body": "@Emz Now than an answer is accepted it may be better to start a new question: otherwise you invalidate existing answers. See for example http://meta.codereview.stackexchange.com/questions/1065/how-to-deal-with-follow-up-questions In future please don't post code for review until after you have run it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T12:06:58.703",
"Id": "66291",
"Score": "0",
"body": "@Emz The reason for ItemSlot separate from Item is so that the same Item can exist in multiple ItemSlot, with a different quantity in each ItemSlot (quantity is a property of ItemSlot not of Item)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:01:22.397",
"Id": "39483",
"ParentId": "39475",
"Score": "2"
}
},
{
"body": "<p>Why use <code>inventory[i].item</code> every time? For performance cache this:</p>\n\n<pre><code>var x = inventory[i].item;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:44:55.237",
"Id": "66151",
"Score": "1",
"body": "C# compiler may be able to make those type of replacements. But it is a good suggestion however. It suits more as a comment than as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T18:10:07.443",
"Id": "66807",
"Score": "0",
"body": "@BrunoCosta I'm not sure. If a have a behaviour in Get Method of the inventory[i].item ? Or have a virtual implementation on this property. Don't make sense compiler cache this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T18:12:58.870",
"Id": "66808",
"Score": "0",
"body": "@AcazSouza I took in account that item is a field, the same would apply if it would be an Auto-Property. But as I stated it is a good suggestion, as you should not rely on compiler."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:41:23.673",
"Id": "39487",
"ParentId": "39475",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39483",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:16:13.180",
"Id": "39475",
"Score": "0",
"Tags": [
"c#",
"unity3d"
],
"Title": "Inventory Script (RPG) in C#"
}
|
39475
|
<p>I've been working on an html5 canvas video player with a lot of fun little extras and ui toys, the main one being a chroma key (green screen) effect that allows the user to key out different colors or ranges of color while the video is playing. </p>
<p>I seem to have hit a snag in the recommended chroma key method. It works, but it is a really heavy process and can tax the cpu to the point where the video will look choppy if the user is running other applications in the background. </p>
<p>Here is the stripped down code I'm using for the chroma key effect:</p>
<pre><code> <video id="sourceVid" controls="true">
<source src="http://s3.amazonaws.com/dfc_attachments/public/documents/3185373/AAA.webm" />
</video>
<canvas id="hCanvas"></canvas>
<canvas id="dCanvas"></canvas>
<script type="text/javascript">
var doc = document;
var sourceVid = doc.getElementById("sourceVid");
var hCanvas = doc.getElementById("hCanvas");
var dCanvas = doc.getElementById("dCanvas");
var hContext = hCanvas.getContext("2d");
var dContext = dCanvas.getContext("2d");
sourceVid.addEventListener('loadeddata', function() {
hCanvas.setAttribute('width', sourceVid.offsetWidth);
dCanvas.setAttribute('width', sourceVid.offsetWidth);
hCanvas.setAttribute('height', sourceVid.offsetHeight);
dCanvas.setAttribute('height', sourceVid.offsetHeight);
}, false);
sourceVid.addEventListener('play', function() {
runAnalysis();
});
var runAnalysis = function() {
if (sourceVid.paused || sourceVid.ended) {
return
}
frameFix();
if (window.requestAnimationFrame) {
requestAnimationFrame(runAnalysis);
} else {
setTimeout(runAnalysis, 0);
}
};
var frameFix = function() {
hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight);
var frame = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight);
var length = frame.data.length;
for (var i = 0; i < length; i++) {
var r = frame.data[i * 4 + 0];
var g = frame.data[i * 4 + 1];
var b = frame.data[i * 4 + 2];
if (g >= 0 && g < 100 && r >= 0 && r < 100 && b >= 0 && b < 100) {
frame.data[i * 4 + 3] = 0;
}
}
dContext.putImageData(frame, 0, 0);
return
};
</code></pre>
<p><strong><a href="http://s3.amazonaws.com/dfc_attachments/public/documents/3186933/GreenScreenEx.html" rel="nofollow">Live Demo</a></strong></p>
<p>Hoping to find ways to further optimize this for performance.</p>
|
[] |
[
{
"body": "<p>Most of your code is API calls. I'm surprised that Javascript is fast enough to run at all (it isn't, on my old laptop, using Chrome browser).</p>\n\n<p>I'll assume that using completely different APIs, and for example writing a plug-in in a different, compiled language (if that's even possible) is out-of-scope for this question.</p>\n\n<p>Therefore I guess that the only performance optimization that's possible/interesting/relevant is of the processing which is implemented in your code, i.e. of the following code fragment:</p>\n\n<pre><code>for (var i = 0; i < length; i++) {\n var r = frame.data[i * 4 + 0];\n var g = frame.data[i * 4 + 1];\n var b = frame.data[i * 4 + 2];\n\n if (g >= 0 && g < 100 && r >= 0 && r < 100 && b >= 0 && b < 100) {\n frame.data[i * 4 + 3] = 0;\n }\n}\n</code></pre>\n\n<p>Perhaps you can do without the multiply-by-4:</p>\n\n<pre><code>length *= 4;\nfor (var i = 0; i < length; i += 4) {\n var r = frame.data[i];\n var g = frame.data[i + 1];\n var b = frame.data[i + 2];\n\n if (g >= 0 && g < 100 && r >= 0 && r < 100 && b >= 0 && b < 100) {\n frame.data[i + 3] = 0;\n }\n}\n</code></pre>\n\n<p>The <a href=\"https://developer.mozilla.org/en/docs/Web/API/ImageData\" rel=\"nofollow\">ImageData contains unsigned numbers</a>, which cannot be negative, so test-for-greater-than-or-equal-to-zero is unnecessary:</p>\n\n<pre><code>length *= 4;\nfor (var i = 0; i < length; i += 4) {\n var r = frame.data[i];\n var g = frame.data[i + 1];\n var b = frame.data[i + 2];\n\n if (g < 100 && r < 100 && b < 100) {\n frame.data[i + 3] = 0;\n }\n}\n</code></pre>\n\n<p>If you do without the temporary variables, then you don't need to deference the color value from the array if an earlier color value fails the test, for example:</p>\n\n<pre><code>length *= 4;\nfor (var i = 0; i < length; i += 4) {\n if (frame.data[i] < 100 && frame.data[i + 1] < 100 && frame.data[i + 2] < 100) {\n frame.data[i + 3] = 0;\n }\n}\n</code></pre>\n\n<p>It may be faster to not dereference from frame each time:</p>\n\n<pre><code>length *= 4;\nvar data = frame.data;\nfor (var i = 0; i < length; i += 4) {\n if (data[i] < 100 && data[i + 1] < 100 && data[i + 2] < 100) {\n data[i + 3] = 0;\n }\n}\n</code></pre>\n\n<p>It's possible that these changes will have no effect on performance: depending on your browser, perhaps they're optimizations which its Javascript compiler is already making.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T02:56:30.280",
"Id": "66470",
"Score": "0",
"body": "Thanks for the response but your suggestion seems to break the green screen effect. The video is still rendered to the canvas, but the desired colors aren't being keyed out. Also I'm comparing with 0 so that colors that fall between rgba(0,0,0,1) and rgba(100,100,100,1) will be keyed out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T02:59:10.417",
"Id": "66471",
"Score": "0",
"body": "This what I'm seeing trying your method: http://s3.amazonaws.com/dfc_attachments/public/documents/3187063/GreenScreenEX.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:28:53.943",
"Id": "66473",
"Score": "0",
"body": "Sorry, you probably realized why I'm comparing with zero... In the full context both 0 and 100 are variables being controlled by sliders, so I kind of need to have both values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T09:59:34.523",
"Id": "66505",
"Score": "0",
"body": "Sorry, I don't see anything wrong with my changes, but I'm not a JavaScript expert so I don't know. I also can't run that code (as it said, it doesn't work on my machine). If it changes functionality, try applying the changes one-by-one, starting from the top (as I wrote them) to see which step of the change is wrong. If you need to keep the test against a lower bond, you can of course keep it: `if (data[i] >= low && data[i] < high && data[i + 1] >= low && data[i + 1] < high && data[i + 2] >= low && data[i + 2] < high)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T14:27:50.067",
"Id": "66517",
"Score": "1",
"body": "@apaul34208 @ChrisW , `length *= 4;` is meaningless, just keep `var length = frame.data.length;` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T17:10:05.697",
"Id": "66536",
"Score": "0",
"body": "@tomdemuyt I wanted to do `var length = frame.data.length * 4;` so that I could increase `i` by `4` each time (`i += 4` instead of `++i`), instead of having several `i*4` expressions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T17:29:59.430",
"Id": "66540",
"Score": "0",
"body": "@ChrisW See my answer building on your answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T17:31:55.507",
"Id": "66541",
"Score": "0",
"body": "@tomdemuyt You're right: +1"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:51:27.543",
"Id": "39620",
"ParentId": "39476",
"Score": "4"
}
},
{
"body": "<p>After back and forth with ChrisW and yourself, it seems I found a glaring bug</p>\n\n<pre><code> var frameFix = function() {\n\n hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight);\n\n var frame = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight);\n\n var length = frame.data.length;\n for (var i = 0; i < length; i++) {\n var r = frame.data[i * 4 + 0];\n var g = frame.data[i * 4 + 1];\n var b = frame.data[i * 4 + 2];\n\n if (g >= 0 && g < 100 && r >= 0 && r < 100 && b >= 0 && b < 100) {\n frame.data[i * 4 + 3] = 0;\n }\n }\n dContext.putImageData(frame, 0, 0);\n return\n };\n</code></pre>\n\n<p>Since in frame.data you have 4 data points per pixel, you only need to go as far as frame.data.length / 4, this should make your code 4 times faster.</p>\n\n<p>This observation with ChrisW's common sense observations makes for:</p>\n\n<pre><code>var frameFix = function() \n{\n hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight);\n\n var frame = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight),\n data = frame.data,\n length = data.length, i;\n\n for (i = 0; i < length; i += 4) \n if (data[i] < 100 && data[i + 1] < 100 && data[i + 2] < 100) \n data[i + 3] = 0;\n\n dContext.putImageData(frame, 0, 0);\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T17:42:57.540",
"Id": "66543",
"Score": "0",
"body": "Your last thought would be wrong; you need to code it as, `for (i = 0; i < length; ) { if (data[i++] >= 100 { i += 3; continue } if (data[i++] >= 100 { i += 2; continue } if (data[i++] >= 100 { i += 1; continue } data[i++] = 0; }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T18:52:22.767",
"Id": "66550",
"Score": "0",
"body": "Updated and removed last thought."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T17:28:50.003",
"Id": "39667",
"ParentId": "39476",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39667",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:32:02.290",
"Id": "39476",
"Score": "7",
"Tags": [
"javascript",
"performance",
"html5",
"canvas",
"video"
],
"Title": "Optimizing the performance of html5 video manipulation"
}
|
39476
|
<p>I came across an issue the other day where I really just could not think of a functional solution. So I fell back on my imperative programming skills. Since a functional solution still eludes me, I figured I'd shout out for some help here.</p>
<h2>Use Case</h2>
<p>I have a List of Strings with arbitrary lengths. These Strings need to be combined into rows that have the same max length.</p>
<p>When a single String's length is greater than max length, that String just gets it's own row as each row eventually get's handled by a function that ensures all Strings are truncated to an appropriate length.</p>
<h3>Example Usage</h3>
<pre><code>scala> val rows = combineStrings(List("Short", "This is a particularly long String...", "More", "Small", "Strings"), 35)
</code></pre>
<h3>Current Output</h3>
<pre><code>scala> rows.foreach(println)
Short
This is a particularly long String...
More, Small, Strings
</code></pre>
<h3>Desired Output</h3>
<pre><code>scala> rows.foreach(println)
Short, More, Small, Strings
This is a particularly long String...
</code></pre>
<h2>Current Solution</h2>
<pre><code>def combineStrings(strs: List[String], maxLen: Int)
: List[String] = {
import scala.collection.mutable.ListBuffer
var scratch = strs.mkString("|")
val rows = ListBuffer[String]()
while (scratch.length > 1) {
scratch.indexOf("|") match {
case idx if (idx == -1 || scratch.length < maxLen) =>
rows += scratch
scratch = ""
case idx if idx > maxLen =>
rows += scratch.substring(0, idx)
scratch = scratch.substring(idx+1)
case idx =>
val lIdx = scratch.lastIndexOf("|", maxLen)
rows += scratch.substring(0, lIdx)
scratch = scratch.substring(lIdx+1)
}
}
rows.toList.map(_.replaceAll("\\|", ", "))
}
</code></pre>
<h3>Notes</h3>
<ul>
<li>Pipes are used because the original Strings are more likely to have their own commas than their own pipes. Maybe other solutions won't need this hackery.</li>
<li>Strings are kept in the same order, but in the end I'd prefer to have the most "compact" rows possible.</li>
</ul>
<h2>Summary</h2>
<p>Any ideas on how to make this more functional would be greatly appreciated. I found several functions in Scala's "String" that looked promising, but I'm not really sure how to integrate them with the length requirements.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:13:16.853",
"Id": "66149",
"Score": "0",
"body": "Can you give an example of input and result?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:54:56.457",
"Id": "66247",
"Score": "0",
"body": "Added example usage section to describe input and current result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T17:53:05.277",
"Id": "66412",
"Score": "0",
"body": "I think what you want is to combine strings into one string (separated by `\", \"`) such that the combined string has length under and as close to `maxLength` as possible without splitting the strings. Furthermore if a string is already over `maxLength` then it is left. Yes? Please clarify (1) do the joined strings have to be under `maxLength` or 'minimally over'? (2) is this an optimization problem - i.e. should the joined length be as close as possible to `maxLength` (3) is order important?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T18:51:58.517",
"Id": "66417",
"Score": "0",
"body": "@samthebest, 1) Joined string length must be <= maxLength; 2) Yes, this is essentially a space optimization solution; 3) Order is not important."
}
] |
[
{
"body": "<p>This is much more \"Functional\" than my first attempt:</p>\n\n<pre><code> def combineStrings(strs: List[String], maxLen: Int)\n : List[String] = {\n import scala.collection.mutable.StringBuilder\n\n strs.map(_.trim).filter(_.nonEmpty)\n .aggregate(List[StringBuilder]())({ (lbs, s) =>\n s.length match {\n case l if (l > maxLen) =>\n new StringBuilder(s) :: lbs\n case l =>\n lbs.find(_.length <= maxLen - (l+2))\n .map { sb => sb ++= s\", $s\"; lbs }\n .getOrElse(new StringBuilder(s) :: lbs)\n }\n }, _ ++ _\n ).map(_.toString).reverse\n }\n</code></pre>\n\n<p>Not sure why I didn't do this the first time around. This solution even provides the desired output, and accounts for the \", \" separators in the length calculations.</p>\n\n<pre><code>scala> val rows = combineStrings(List(\"Short\", \"This is a particularly long String...\", \"More\", \"Small\", \"Strings\"), 35)\nrows: List[String] = List(Short, More, Small, Strings, This is a particularly long String...)\n\nscala> rows.foreach(println)\nShort, More, Small, Strings\nThis is a particularly long String...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T02:30:51.973",
"Id": "39708",
"ParentId": "39477",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39708",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:37:15.903",
"Id": "39477",
"Score": "2",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Functional Re-Write in Scala: Rows of Strings with a Max Width"
}
|
39477
|
<p>Just looking for some feedback on a hangman script. It works perfectly fine; I'm just trying to master the Python language, and the best place way to get better is to ask the <em>true</em> masters!</p>
<pre><code>import random
UNKNOWN_CHARACTER = "*"
GUESS_LIMIT = 7
words = []
def load_words():
global words
with open("dictionary.txt") as file:
words = file.readlines()
stripped = []
for word in words:
stripped.append(word.strip())
words = stripped
def play():
word = random.choice(words)
solved = False
constructed = ""
guessed = []
guess = ""
for i in range(0, len(word)):
constructed += UNKNOWN_CHARACTER
while not solved and len(guessed) < GUESS_LIMIT:
print("\n" + str(GUESS_LIMIT - len(guessed)) + " errors left...")
print(constructed)
valid_guess = False
while not valid_guess:
guess = input("Guess a letter: ").lower()
if len(guess) == 1:
if guess not in guessed and guess not in constructed:
valid_guess = True
else:
print("You've already guessed that letter!")
else:
print("Please guess a single letter.")
if guess in word:
new_constructed = ""
for i in range(0, len(word)):
if word[i] == guess:
new_constructed += guess
else:
new_constructed += constructed[i]
constructed = new_constructed
else:
guessed.append(guess)
solved = constructed == word
print("\n" + word)
def main():
load_words()
keep_playing = True
while keep_playing:
play()
keep_going = input("Continue playing? (y/n): ").lower()
if keep_going not in ["yes", "y"]:
keep_playing = False
if __name__ == "__main__":
main()
</code></pre>
<p>Excerpt of <code>dictionary.txt</code>:</p>
<pre><code>logorrheic
logos
logotype
logotypes
logotypies
logotypy
logroll
logrolled
logroller
logrollers
logrolling
logrollings
logrolls
logs
logway
logways
logwood
logwoods
logy
loin
loincloth
loincloths
loins
loiter
loitered
loiterer
loiterers
loitering
loiters
loll
lollapalooza
lollapaloozas
lolled
loller
lollers
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:00:50.367",
"Id": "66157",
"Score": "1",
"body": "Can you provide an example of dictionnary.txt ?"
}
] |
[
{
"body": "<p><strong>List comprehension</strong> is a very neat way to construct lists in Python. For instance :</p>\n\n<pre><code>stripped = []\nfor word in words:\n stripped.append(word.strip())\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>stripped = [word.strip() for words in word]\n</code></pre>\n\n<p>(and then you can get rid of the <code>stripped</code> variable altogether in your code).</p>\n\n<hr>\n\n<p>The pythonic way to loop over something is not to use <code>range</code> and <code>len</code> (except if you really have to). For instance, we have first :</p>\n\n<pre><code>for i in range(0, len(word)):\n constructed += UNKNOWN_CHARACTER\n</code></pre>\n\n<p>which can be written :</p>\n\n<pre><code>for i in word:\n constructed += UNKNOWN_CHARACTER\n</code></pre>\n\n<p>Then one might argue that you can use the <code>*</code> operator here to write :</p>\n\n<pre><code>constructed = UNKNOWN_CHARACTER * len(word)\n</code></pre>\n\n<hr>\n\n<p>Sometimes, you might think that you need to use <code>range</code> and <code>len</code> because you need the index corresponding to your iteration. This is what <code>enumerate</code> is for. For instance :</p>\n\n<pre><code> new_constructed = \"\"\n for i in range(0, len(word)):\n if word[i] == guess:\n new_constructed += guess\n else:\n new_constructed += constructed[i]\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code> new_constructed = \"\"\n for i,l in enumerate(word): # i in the index, l is the letter\n if l == guess: # note that we don't need to get the i-th element here\n new_constructed += l # I prefer l to guess here because it's shorter :-P\n else:\n new_constructed += constructed[i]\n</code></pre>\n\n<p>What would be really awesome here would to be to be able to iterate over 2 containers in the same time. <code>zip</code> allows you to do such a thing.</p>\n\n<pre><code> new_constructed = \"\"\n for w,c in zip(word,constructed):\n if w == guess:\n new_constructed += w\n else:\n new_constructed += c\n</code></pre>\n\n<p>Then, it's pretty cool because we can make things slightly more concise :</p>\n\n<pre><code> new_constructed = \"\"\n for w,c in zip(word,constructed):\n new_constructed += w if w == guess else c\n</code></pre>\n\n<p>If you want to play it cool and re-use list comprehension (or even <strong>generator expression</strong> (I use fancy words so that you can google then if required)) : you build some kind of list of characters/strings and join them together with <code>join</code>.</p>\n\n<pre><code> new_constructed = ''.join((w if w == guess else c for w,c in zip(word,constructed)))\n</code></pre>\n\n<p>This being said, I probably wouldn't build that string this way but I just pointed to point this out so that you can discover new things.</p>\n\n<hr>\n\n<p>Usually, global variables are frowned upon because they make things hard to track. In your case, it is not so much of an issue but let's try to split the logic in smaller parts. It makes things easier to understand and to test too.</p>\n\n<p>Here, we just need to return the list of words from <code>load_words</code>.</p>\n\n<hr>\n\n<p>It's interesting to store the letters that have been guessed. However, a <code>list</code> (build with <code>[]</code> and populated with <code>append()</code>) might not be the right container for this. What you really want at the end of the day is just to be able to tell quickly whether some letter has been guessed already. This is what <code>set</code>s are for.</p>\n\n<hr>\n\n<p>You could store all guesses or just wrong guesses. You've decided to store only wrong guesses (as right guesses can be deduced from the <code>constructed</code> string).</p>\n\n<p>Personnally, I'd rather save all guesses on one hand and the number of wrong guesses on the other hand at it might make things a bit easier later on. I am not saying that what you did was wrong at all, I just want to show a different way to do.</p>\n\n<p>Also, I'm trying to split the logic used to </p>\n\n<ol>\n<li>display what has been found away from the logic used to </li>\n<li>know if a letter has been guessed</li>\n<li>know if the character has been fully found.</li>\n</ol>\n\n<p>At the moment, the variable <code>constructed</code> in used for these 3 things and can make things hard to understand.</p>\n\n<p>At the end, here is what I came up with :</p>\n\n<pre><code>#!/usr/bin/python\n\nimport random\n\nUNKNOWN_CHARACTER = \"*\"\nGUESS_LIMIT = 7\n\ndef load_words():\n words = []\n with open(\"dictionary.txt\") as file:\n words = file.readlines()\n return [word.strip() for word in words]\n\ndef play(word):\n nb_wrong = 0\n guesses = set()\n while nb_wrong < GUESS_LIMIT:\n print(\"\\n\" + str(GUESS_LIMIT - nb_wrong) + \" errors left...\")\n print(''.join(c if c in guesses else UNKNOWN_CHARACTER for c in word))\n while True:\n guess = input(\"Guess a letter: \").lower()\n if len(guess) == 1:\n if guess in guesses:\n print(\"You've already guessed that letter!\")\n else:\n guesses.add(guess)\n break # stop when we have a valid guess \n else:\n print(\"Please guess a single letter.\")\n if all(c in guesses for c in word):\n break # stop when all characters are found\n print(\"\\n\" + word)\n\n\ndef main():\n words = load_words()\n while True:\n play(random.choice(words))\n if input(\"Continue playing? (y/n): \").lower() not in [\"yes\", \"y\"]:\n break\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>(It's highly not tested but the point was more to explain you what I did than to show you a working program)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T17:56:40.570",
"Id": "68762",
"Score": "0",
"body": "very minor tweak - I would put the single character test first: `if len(guess) != 1: print(\"Please guess a single letter.\"); continue` which would save an indentation level for the non-error case and potentially make `play` more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T08:34:55.423",
"Id": "69901",
"Score": "0",
"body": "I guess it's a matter of personal preference. I prefer it the way it currently is but I understand your point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:56:06.120",
"Id": "39496",
"ParentId": "39484",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39496",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T16:17:12.930",
"Id": "39484",
"Score": "2",
"Tags": [
"python",
"game",
"python-3.x",
"hangman"
],
"Title": "Python Hangman feedback"
}
|
39484
|
<p>I make some ui custom controls. Typically my controls have themes to them so it can be changed. I dont use css files for each themes. What I do instead is hava a javascript file that contains the different themes for that particular control. Example of my button control (Note i took the rest of the css off the other colors just so this wont be so long in the post) </p>
<pre><code>(function ($) {
$.fn.buttonTheme = function () { };
$.buttonTheme = {
newButtonTheme: function(){
$.buttonTheme.rules = {
"button" :
{
"nonrounded": "cursor: pointer; cursor: hand;display:inline-block;zoom:1;*display:inline;" +
"vertical-align:baseline;margin:0 2px;outline:none;text-shadow:0 1px 1px rgba(0,0,0,.3);" +
"-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);" +
"-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);box-shadow:0 1px 2px rgba(0,0,0,.2);",
"rounded": "cursor: pointer; cursor: hand;display:inline-block;zoom:1;*display:inline;vertical-align:baseline;margin:0 2px;" +
"outline:none;text-shadow:0 1px 1px rgba(0,0,0,.3);-webkit-border-radius:.4em;-moz-border-radius:.4em;" +
"border-radius:.4em;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.2);-moz-box-shadow:0 1px 2px rgba(0,0,0,.2);" +
"box-shadow:0 1px 2px rgba(0,0,0,.2);"
},
"light_gray":
{
"enabled": "" +
"",
"disabled": "",
"hover": "",
"text": ""
},
"black":
{
"enabled": "",
"disabled": "",
"hover": "",
"text": ""
},
"gray":
{
"enabled": "",
"disabled": "",
"hover": "",
"text": ""
},
"white":
{
"enabled": "",
"disabled": "",
"hover": "",
"text": ""
}
};
}
};
})(jQuery);
</code></pre>
<p>So in the control javascript file I build the control by assigning the particular elements the particular style it needs based on the selected theme like ligh_gray. I find this method to be easy to maintain and update to other themes because the underlying samples are there and its not hard coded in the script. So I can just create another theme like aqua for example and just change the colors, etc. Also I can dynamically change the theme easier without having to do a page refresh</p>
<p>What I wanted to know from others is there thoughts on this. Is there a performance issue in this method? Does it seem like its a maintenance headache? </p>
|
[] |
[
{
"body": "<p>Yes! This looks like a maintenance head ache ( nightmare ).</p>\n\n<p>CSS belongs to CSS files ( you can apply csslint to CSS files, CSS files also have syntax highlighting, plus most developers rightfully dislike maintaining CSS in JavaScript ).</p>\n\n<p>If you must support different styles at run-time, you can create styles in your stylesheet for each theme and then assign the right class when themes get switched.</p>\n\n<p>To your points:</p>\n\n<ul>\n<li>I find this method to be easy to maintain and update to other themes because the underlying samples are there and its not hard coded in the script. <em>I am not sure what you mean by \"not hardcoded\", but you are most likely wrong.</em></li>\n</ul>\n\n\n\n<ul>\n<li><p>So I can just create another theme like aqua for example and just change the colors, etc. <em>You can do the same with CSS files</em></p></li>\n<li><p>Also I can dynamically change the theme easier without having to do a page refresh. <em>You can do the same by changing the class dynamically</em></p></li>\n</ul>\n\n<p>As for performance, you are using extra bandwidth by sending over all style-sheets, to be avoided on mobile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T20:23:50.680",
"Id": "66559",
"Score": "0",
"body": "Thanks for the input. Im feeling the same also. It was approach that I took but wanted to see what others thought about it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T16:20:16.910",
"Id": "39663",
"ParentId": "39489",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39663",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:22:41.933",
"Id": "39489",
"Score": "2",
"Tags": [
"javascript",
"css"
],
"Title": "Performance Issue on css and javascript styling"
}
|
39489
|
<p>I would like to get some feedback on my code. I am starting to program after doing a few online Python courses.</p>
<p>Would you be able to help me by following my track of thinking and then pinpointing where I could be more efficient? (I have seen other answers but they seem to be more complicated than they need to be, albeit shorter; but perhaps that is the point).</p>
<p>Question:</p>
<blockquote>
<p>Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p>
<p>By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.</p>
</blockquote>
<pre><code>fibValue = 0
valuesList = []
a = 0
b = 1
#create list
while fibValue <= 4000000:
fibValue = a + b
if fibValue % 2 == 0:
valuesList.append(fibValue)
a = b
b = fibValue
print (valuesList) #just so that I can see what my list looks like after fully compiled
print() #added for command line neatness
print() #added for command line neatness
newTot = 0
for i in valuesList:
newTot += i
print (newTot)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T05:22:01.037",
"Id": "66169",
"Score": "0",
"body": "`append()` isn't on the list of efficient ways to populate a list. [Comprehensions](http://www.diveintopython3.net/comprehensions.html) are a means of accomplishing the same thing but more efficiently (in Python). `squares = [ a**2 for a in range(2,100) ]` It's not quite so simple for Fibonacci, but the concept is worth using."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T06:24:30.270",
"Id": "66172",
"Score": "1",
"body": "You should also check out [`sum()`](http://docs.python.org/dev/library/functions.html#sum)."
}
] |
[
{
"body": "<p>The Fibonacci sequence is a problem that's very well suited for a recursive solution. If you haven't yet learned about recursion, I would highly recommend it, as it provide a whole new way of looking at problems. </p>\n\n<p>To find the nth Fibonacci number, you could use something like the following.</p>\n\n<pre><code>def fibonacci(n):\n if n < 2: return n\n return fibonacci(n-1)+fibonacci(n-2)\n\nfibonacci(10) # returns 55\n</code></pre>\n\n<p>The reason that this answer is so clean is because it's framed in the same way that the fibonacci sequence is framed. To find one fibonacci number, you simply need to know the previous two. </p>\n\n<p>That being said, recursion does introduce some interesting issues. To find the 100th fibonacci number it takes a surprising amount of time. Often problems like these require caching for recursion to be efficient. </p>\n\n<p>What if we approached the problem from the opposite direction? Instead of starting from the top and working our way down, we could start from the bottom and work our way up. State is then stored in the arguments of the function. </p>\n\n<pre><code>def fibonacci(a, b, n):\n if n < 3: return a + b\n return fibonacci(b, a+b, n-1)\n\nfibonacci(0, 1, 10) # returns 55\n</code></pre>\n\n<p>I hope you've enjoyed this little taste of recursion. Let me know if anything is unclear, and I'll be glad to help clear things up. However, if efficiency is your goal, Python's recursion might not be the best.</p>\n\n<p>If recursion isn't your thing, or if you're intending to calculate <strong>very</strong> large fibonacci numbers, you might want an iterative solution (in fact, your own solution is pretty good). An iterative solution works especially well if you're looking for the largest fibonacci number less than n.</p>\n\n<pre><code>def fibonacci(n):\n # finds the largest fibonacci number less than n\n a, b = 0, 1\n while(a+b) < n:\n a, b = b, a+b\n return b\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T04:59:31.123",
"Id": "66173",
"Score": "5",
"body": "Recursion is not always a good solution in Python, however, because Python doesn't implement tail recursion and, more generally, isn't designed to support recursive algorithms that are equally well-handled via iteration. If you try to call `fibonacci(0, 1, 1000)`, you'll hit a `RuntimeError` because you'll have exceeded the maximum recursion depth. Of course, the 1000th Fibonacci number is much, much larger than 4 million, but this is still an issue worth keeping in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T05:00:48.977",
"Id": "66174",
"Score": "0",
"body": "Yup, definitely a concern. I didn't now how much detail I should go into there, but the python maximum recursion depth is definitely a problem that you could run into."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T05:01:38.567",
"Id": "66175",
"Score": "1",
"body": "Right, it certainly isn't an issue here, but I figured it was worth mentioning, since (if I remember right) some of the later Project Euler problems do require very deep recursions if implemented recursively."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T05:07:42.857",
"Id": "66176",
"Score": "1",
"body": "In the event that the OP does run into a max recursion depth issue, `sys.setrecursionlimit(n)` is your friend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T06:37:46.647",
"Id": "66177",
"Score": "0",
"body": "@MadisonMay ...which may cause uncaught overflows (I don't remember where I read it)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:22:09.217",
"Id": "66178",
"Score": "0",
"body": "Fair point -- it's your best friend and your worst enemy."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T04:51:39.277",
"Id": "39494",
"ParentId": "39493",
"Score": "1"
}
},
{
"body": "<p>A hint that I always offer people with this specific question. Take a look at the first few numbers of the sequence - I have set the even ones in bold:</p>\n\n<p>1, 1, <strong>2</strong>, 3, 5, <strong>8</strong>, 13, 21, <strong>34</strong>, 55, 89, <strong>144</strong>...</p>\n\n<p>Can you see a pattern in the spacing? Can you explain (ideally, prove) it?</p>\n\n<p>Given that, can you think of a way to generate even Fibonacci numbers directly, instead of filtering through for them? (Hint: start with (1,2), and try to generate (5,8) in one step, then (21, 34) etc. Do some algebra and figure out how to apply multiple iterations of the generation rule at once.)</p>\n\n<p>Anyway, in terms of doing the actual calculation with the numbers, there are more elegant approaches. Instead of asking Python to build a list directly, we can write a <em>generator</em>:</p>\n\n<pre><code>def even_fibonacci_up_to(n):\n a, b = 1, 2\n while b <= n:\n yield b # since 2 qualifies, after all.\n # Now calculate the next value.\n # math from the first step goes here when you figure it out!\n</code></pre>\n\n<p>Notice the use of the <code>yield</code> keyword. This lets us treat our expression <code>even_fibonacci_up_to(4000000)</code> as a special sort of sequence whose elements are generated on-demand. Unlike with ordinary functions which can only <code>return</code> once. :) (Using <code>return</code> inside a generator terminates the whole process of <code>yield</code>ing values when it is reached.)</p>\n\n<p>And instead of looping through this sequence to add up the numbers, we can use the built-in <code>sum</code> function:</p>\n\n<pre><code>sum(even_fibonacci_up_to(4000000))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T05:19:34.320",
"Id": "39495",
"ParentId": "39493",
"Score": "7"
}
},
{
"body": "<p>Your method isn't bad though it could be cleaned up and I have a faster and more straight forward suggestion, say using a simple class.</p>\n\n<ul>\n<li>Karl Knechtel's method appears to create a near infinite loop.</li>\n<li>Madison May's recursion method reaches a \"RuntimeError: maximum recursion depth exceeded\" beyond an input of 40. But the 3rd solution they suggest appears to execute without error but the output appears inaccurate... I believe you are only getting the largest number, idk. Mine is similar. </li>\n</ul>\n\n<p>I think this is your best, most accurate, and simplest (also fastest given a correct solution):</p>\n\n<pre><code>def fib(n): # return Fibonacci series up to n\n result, a, b = list(), 0, 1 # set variables\n result.append(0) # Initial Fibonacci Zero\n while b < n:\n if b % 2 == 0:\n result.append(b)\n a, b = b, a+b\n return result\n\ndef fibSum(n):\n return sum(map(int, fib(n)))\n\nprint(fibSum(4000000))\n</code></pre>\n\n<p>Hope this helps. Good luck!</p>\n\n<p>P.S. Also, I would recommend using '\\n' for new line when printing for code cleanness, there's no need for several print statements but we all start somewhere and I've only been programming Python for about a year myself but I also have other languages in my background and I read a lot. A few key notes: map allows you to easily sum up a list of ints/truple and you can use sum instead of incrementing through a list and adding it up, it should be faster in 'almost' all cases (strings are a different story). Again, good luck!</p>\n\n<p>P.P.S. I kept your mod 2, modulus is your friend. Modifying built in perimeters is not your friend, if you have to do that, odds are you're doing something wrong. Just food for thought.</p>\n\n<p>Benchmarks:</p>\n\n<p>Your Code:<br />\nOutput: 4613732<br />\nTotal Run Time: 0.000175 seconds in Python<br />\nTotal Run Time: 0.000069 seconds in Pypy</p>\n\n<p>My Suggestion:<br />\nOutput: 4613732<br />\nTotal Run Time: 0.000131 seconds in Python<br />\nTotal Run Time: 0.000053 seconds in Pypy<br /></p>\n\n<p><strong>Edit:</strong> Alternatively, you could just use this:</p>\n\n<pre><code>def fib2(n):\n result, a, b = 0, 0, 1\n while b < n:\n if b % 2 == 0:\n result += b\n a, b = b, a+b\n return result\n\nprint(fib2(4000000))\n</code></pre>\n\n<p>I personally prefer for whatever reason to have the Fibonacci actually functional on it's own as apposed to building a single purpose class. Obviously it should be slightly faster but I haven't tested it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-25T07:58:12.330",
"Id": "254479",
"Score": "0",
"body": "This problem is a good scenario for using generator : the `fib` function shouldn't need to be concerned about where the values it generates are put and in your case, you don't even need a temporary list. @Karl's answer ( http://codereview.stackexchange.com/a/39495/9452 ) is a good example of this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-25T07:40:54.880",
"Id": "135823",
"ParentId": "39493",
"Score": "2"
}
},
{
"body": "<h2>Optimizations</h2>\n\n<h3>Eliminate the list</h3>\n\n<p>The first and most important optimization is to not use a list:</p>\n\n<ul>\n<li>There's no need to remember each even Fibonacci number; the sum is what we ultimately care about, and we can just add each even Fibonacci number onto the sum as we go along, then forget about that even Fibonacci number</li>\n<li>It takes time to create, store numbers into, retrieve numbers out of, and increase the size of (when you need to go beyond the current list capacity) the list</li>\n<li>It takes time to delete the list later on</li>\n</ul>\n\n<h3>Eliminate the check for evenness</h3>\n\n<p>Much less important is that you don't need to check for evenness because even Fibonacci numbers come exactly every three Fibonacci numbers. You can just blindly add every third Fibonacci number onto the sum with no check for evenness. This is because:</p>\n\n<ul>\n<li>Odd + even = odd, so the next Fibonacci after an even is odd</li>\n<li>Even + odd = odd, so the next Fibonacci after that is also odd</li>\n<li>Odd + odd = even, so the next Fibonacci number after the two odds is even again</li>\n<li>The cycle then repeats</li>\n</ul>\n\n<h2>Algorithm</h2>\n\n<ul>\n<li>Start with the first even Fibonacci number</li>\n<li>While the current even Fibonacci doesn't exceed your limit:\n\n<ul>\n<li>Add it to your sum</li>\n<li>Skip ahead to the third Fibonacci number after that, which will be the next even Fibonacci number</li>\n</ul></li>\n<li>Return the sum</li>\n</ul>\n\n<p> </p>\n\n<pre><code>def solve(limit):\n sum = 0\n a = 2\n b = 3\n while a <= limit:\n sum += a\n c = a + b\n d = b + c\n e = c + d\n a = d\n b = e\n return sum\n</code></pre>\n\n<h2>Simplified algorithm</h2>\n\n<p>Since <code>a</code> and <code>b</code> are just filled in with <code>d</code> and <code>e</code>, we can carefully simplify away those extra variables:</p>\n\n<pre><code>def solve(limit):\n sum = 0\n a = 2\n b = 3\n while a <= limit:\n sum += a\n c = a + b\n a = b + c\n b = c + a\n return sum\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-26T04:32:11.763",
"Id": "135920",
"ParentId": "39493",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T04:31:13.450",
"Id": "39493",
"Score": "7",
"Tags": [
"python",
"project-euler",
"fibonacci-sequence"
],
"Title": "More efficient solution for Project Euler #2 (sum of Fibonacci numbers under 4 million)"
}
|
39493
|
<p>I need a little help with improving my first Java program. I have programmed for about a month, so my code is quite messy. The program is a "Musiclist" program, with which you can add songs, edit songs, and remove songs from the list.</p>
<p>The program uses 2 <code>ArrayList</code>s, to store the information about the song (Song name, Artist), which will be stored to the <code>arraylist(indexnumber)</code>.</p>
<p>What I need help with is:</p>
<ul>
<li>Make it less messy. Maybe add <code>ActionListeners</code> to another class?</li>
<li>The song- and artist <code>ArrayList</code> that shares index seems like a bad idea. I always have to perform 2 actions like song.add(index) and artist.add(index). Maybe a 2D <code>ArrayList</code>?</li>
<li>I need to add the songs to a database I can call it from, when I open the program next time.</li>
</ul>
<p>If you have any new suggestions for my program, I would love to include them.</p>
<pre><code>public class MusicList extends JFrame{
public JTextField af;
private JList jl;
private JButton add;
private JButton edit;
private JButton test;
private JPanel jp;
private JScrollPane sp;
private JTextField artist;
private JButton save;
private JButton listb;
private JPopupMenu jpo;
private JMenuItem ite;
private JButton editsave;
private JButton editlist;
int g;
//creates a DefaultListModel.. actions at the JList can be made through here. e.g if adding to jlist is m.addElement();
DefaultListModel<String> m = new DefaultListModel<String>();
//creates arraylists
List<String> fl = new ArrayList<String>();
List<String> art = new ArrayList<String>();
public MusicList(){
super("Musiclist");
setLayout(null);
jl = new JList(m);
add(jl);
//creates a scrollpane, "implements jlist"
sp = new JScrollPane(jl);
sp.setBounds(30,20,150,140);
add(sp);
//creates the textfield to contain songname
af = new JTextField(12);
String afs = af.getText();
af.setBounds(20,20,170,20);
add(af);
af.setVisible(false);
//opens the add menu
add = new JButton("add");
add.setBounds(20,180,80,20);
add(add);
//opens the edit menu
edit = new JButton("edit");
edit.setBounds(110,180,80,20);
add(edit);
//this button checks if art and fl(arraylists) match to the index.
test = new JButton("test");
test.setBounds(200, 40, 80, 20);
add(test);
//the textfield which will pass the artist string.. used in add and edit
artist = new JTextField();
artist.setBounds(20,50,170,20);
add(artist);
artist.setVisible(false);
//adds back button in "add" menu
listb = new JButton("back");
listb.setBounds(110,180,80,20);
add(listb);
listb.setVisible(false);
//adds save button on "add" menu
save = new JButton("save");
save.setBounds(20,180,80,20);
add(save);
save.setVisible(false);
//adds the back button on "edit" menu
editlist = new JButton("back");
editlist.setBounds(110, 180, 80, 20);
add(editlist);
editlist.setVisible(false);
//adds the save button on "edit" menu
editsave = new JButton ("save");
editsave.setBounds(20,180,80,20);
add(editsave);
editlist.setVisible(false);
//button to open the add window
add.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
jl.setVisible(false);
sp.setVisible(false);
add.setVisible(false);
edit.setVisible(false);
listb.setVisible(true);
save.setVisible(true);
af.setVisible(true);
artist.setVisible(true);
af.requestFocus();
}});
edit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.out.println(jl.getSelectedIndex());
//checks if theres an selected index.. unselected index = -1.
if(jl.getSelectedIndex()<0){
JOptionPane.showMessageDialog(null, "Please select a song to edit");
}else{
//open edit window
jl.setVisible(false);
sp.setVisible(false);
add.setVisible(false);
edit.setVisible(false);
editlist.setVisible(true);
editsave.setVisible(true);
af.setVisible(true);
artist.setVisible(true);
//takes selected index, and set text of textfield af and artists to selected index.
final int i = jl.getSelectedIndex();
if(i>=0){
System.out.println(i);
af.setText(fl.get(i));
artist.setText(art.get(i));
}}}});
//test button.. checks if index + song + artist match.
test.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
final int i = jl.getSelectedIndex();
if(i>=0){
//String j = (m.getElementAt(i));
//System.out.println(j);
System.out.println(fl.get(i));
System.out.println(art.get(i));
}}});
jl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
//adds a actionlistener to Jlist
JList jl = (JList)evt.getSource();
//if double click---
if (evt.getClickCount() == 2) {
//
int index = jl.locationToIndex(evt.getPoint());
//location to youtube link will be here.
} else if (evt.getClickCount() == 3) { // Triple-click
int index = jl.locationToIndex(evt.getPoint());
}}});
//listb is the "back to list" button.
listb.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
//if u are at add window, listb will take u back to the list of songs.
jl.setVisible(true);
sp.setVisible(true);
add.setVisible(true);
edit.setVisible(true);
listb.setVisible(false);
save.setVisible(false);
af.setVisible(false);
artist.setVisible(false);
}});
save.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
//takes the afart, and save it to the JList(first passed to addString)
String getart = artist.getText();
String getaf = af.getText();
String afart = (getaf+" - "+getart);
//pass afart to addString method
addString(getaf,getart);
af.setText(null);
jl.requestFocus();
artist.setText(null);
//set the window back to "list of songs"
jl.setVisible(true);
sp.setVisible(true);
add.setVisible(true);
edit.setVisible(true);
listb.setVisible(false);
save.setVisible(false);
af.setVisible(false);
artist.setVisible(false);
}});
//adds another mouselistener to jl
jl.addMouseListener(
new MouseAdapter(){
public void mousePressed(MouseEvent e) {check(e);}
public void mouseReleased(MouseEvent e) {check(e);}
//mouse event right click
public void check(MouseEvent e) {
if (e.isPopupTrigger()) { //if the event shows the menu
jl.setSelectedIndex(jl.locationToIndex(e.getPoint())); //select the item
//creates a popupmenu.
JPopupMenu jpo = new JPopupMenu();
//creates a item that links to popupmenu.. JMenuItem works like a button
//this JMenuItem is a remove button
JMenuItem ite = new JMenuItem("remove");
jpo.add(ite);
jpo.show(jl, e.getX(), e.getY()); //and show the menu
//JMenuItem actionListener.
ite.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//takes selectedIndex, and remove it from the two arraylist, + the Modellist(jlist)
final int i = jl.getSelectedIndex();
if(i>=0){
m.removeElementAt(i);
fl.remove(i);
art.remove(i);
}}});}}});
//ActionListener for the back button in the edit menu
editlist.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
jl.setVisible(true);
sp.setVisible(true);
add.setVisible(true);
edit.setVisible(true);
editlist.setVisible(false);
editsave.setVisible(false);
af.setVisible(false);
artist.setVisible(false);
af.setText(null);
artist.setText(null);
}});
//ActionListener for the save buttin in the edit menu
editsave.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//takes 2 string, and the int from getSelected index, and pass it to editSong(); method.
String aff = af.getText();
String artt = artist.getText();
final int f = jl.getSelectedIndex();
//System.out.println(f);
editSong(f,aff,artt);
//close the edit window
jl.setVisible(true);
sp.setVisible(true);
add.setVisible(true);
edit.setVisible(true);
editlist.setVisible(false);
editsave.setVisible(false);
af.setVisible(false);
artist.setVisible(false);
}});
}
//addString method adds new string to JList, and put them at the next avaiable index.
public void addString(String o, String l){
//adds the songname and artistname to the arratlist.
fl.add(o);
art.add(l);
String p = (o+" - "+l);
//adds the artists+songname to the jlist.
m.addElement(p.toString());
}
public void editSong(int i, String song, String artt){
String s = song;
String a = artt;
String sa = (s+" - "+a);
//fl.add(i,null);
//remove object at the indexnumber "i"(current index selected) from arraylists.
fl.remove(i);
art.remove(i);
//adds the new string passed in from "editsave", and put them to selectedIndex..
fl.add(i,s);
art.add(i,a);
//remove old JList element, and put in the new.
m.removeElementAt(i);
m.add(i,sa);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>UI code is usually kinda \"messy\" you could separate out the ActionListeners to new files if you want. Also I'd probably put Artist and Song Title into a class like </p>\n\n<pre><code>public class SongData {\n private String artist;\n private String title;\n public SongData( String title, String artist ) {\n this.artist = artist;\n this.title = title;\n }\n}\n</code></pre>\n\n<p>And then maybe throw those in your array or use an ArrayList to store them. Or if you wanted to look them up later by either field you could put them in a Map</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:50:30.283",
"Id": "39501",
"ParentId": "39498",
"Score": "5"
}
},
{
"body": "<p>For cleaning up your code a bit,</p>\n\n<ol>\n<li>Avoid using abbreviations for your variables. If some other coder comes along and looks halfway through your massive class file, they will think what is a 'js'?</li>\n<li><p>Try to create methods for repeating code. For example, your adding lots of JButtons repeatedly. I'm not a UI expert but I think you can try something like this...</p>\n\n<pre><code>private void addJButton(JButton button, String name, Rectangle rectangle){\n button = new JButton(name);\n button.setBounds(rectangle.getBounds()); \n add(button); \n}\n</code></pre></li>\n</ol>\n\n<p>Then your code will look like this, which is much more readable, and will cut out about 3 lines of code per JButton (Note: some JButtons your setting visibility, you could overload a method for those as well, or include a boolean in above method for handling that in ALL JButtons)</p>\n\n<pre><code>addJButton(add, \"add\", new Rectangle(20, 180, 80, 20));\naddJButton(edit, \"edit\", new Rectangle(110, 180, 80, 20));\n</code></pre>\n\n<p>As far as seperating your Action listeners, I agree with Roberts above comment. If you decide not to place them in a seperate file, I would at least seperate them into a private method, something like private void setActionListeners. </p>\n\n<p>In general I like to modularize my code so it reads as close to this as possible...</p>\n\n<pre><code>public void someMainMethod(){\n initialize();\n calculations();\n someMoreCalculations();\n iReadLikeABook();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T05:00:55.217",
"Id": "39717",
"ParentId": "39498",
"Score": "6"
}
},
{
"body": "<p>You are calling a variation of this code five times!</p>\n\n<pre><code>jl.setVisible(false);\nsp.setVisible(false);\nadd.setVisible(false);\nedit.setVisible(false);\nlistb.setVisible(true);\nsave.setVisible(true);\naf.setVisible(true); \nartist.setVisible(true);\n</code></pre>\n\n<p>The only difference being that you switch <code>false</code> to <code>true</code> and vice-versa on some of the calls.</p>\n\n<p>I would create a method for this,</p>\n\n<pre><code>private void applyVisibilities(boolean sectionAVisible) {\n jl.setVisible(sectionAVisible);\n sp.setVisible(sectionAVisible);\n add.setVisible(sectionAVisible);\n edit.setVisible(sectionAVisible);\n listb.setVisible(!sectionAVisible);\n save.setVisible(!sectionAVisible);\n af.setVisible(!sectionAVisible); \n artist.setVisible(!sectionAVisible);\n}\n</code></pre>\n\n<p>Then you can replace these lines in the rest of your code with <code>applyVisibilities(true)</code> or <code>applyVisibilities(false)</code>.</p>\n\n<p>I suggest naming the <code>sectionAVisible</code> parameter to something that makes more sense for you.</p>\n\n<hr>\n\n<p>In addition to this, I also suggest adding <code>final</code> to all possible fields in your class. Once your <code>JButton</code>s and <code>JTextField</code>s has been created, they shouldn't be recreated again, right?</p>\n\n<pre><code>private final JButton editlist;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:28:03.860",
"Id": "43791",
"ParentId": "39498",
"Score": "5"
}
},
{
"body": "<p>Just two quick notes:</p>\n\n<ol>\n<li><p>A great comment from <a href=\"https://codereview.stackexchange.com/a/19459/7076\"><em>@tb-</em>'s answer</a>:</p>\n\n<blockquote>\n <p>Do not extend <code>JPanel</code>, instead have a private <code>JPanel</code> \n attribute and deal with it (Encapsulation). \n There is no need to give access to all \n <code>JPanel</code> methods for code dealing with a <code>UserPanel</code>\n instance. If you extend, you are forced to stay with this forever, \n if you encapsulate, you can change whenever you want without \n taking care of something outside the class.</p>\n</blockquote>\n\n<p>(Substitute <code>JPane</code> with <code>JFrame</code>.)</p></li>\n<li><p>The following fields could be private:</p>\n\n<blockquote>\n<pre><code>DefaultListModel<String> m = new DefaultListModel<String>();\n//creates arraylists\nList<String> fl = new ArrayList<String>();\nList<String> art = new ArrayList<String>();\n</code></pre>\n</blockquote>\n\n<p>(<a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:35:55.010",
"Id": "43792",
"ParentId": "39498",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:13:56.370",
"Id": "39498",
"Score": "4",
"Tags": [
"java",
"beginner",
"database"
],
"Title": "Music list program"
}
|
39498
|
<p>I found a function online that tests if a tree is a binary search tree:</p>
<pre><code>private boolean isBST(Node node) {
if (node==null) return(true);
// do the subtrees contain values that do not
// agree with the node?
if (node.left!=null && maxValue(node.left) > node.data) return(false);
if (node.right!=null && minValue(node.right) <= node.data) return(false);
// check that the subtrees themselves are ok
return( isBST(node.left) && isBST(node.right) );
}
</code></pre>
<p>I don't quite understand why <code>maxValue</code> and <code>minValue</code> are being used.</p>
<p>Here is the code for both functions:</p>
<pre><code>private int minValue(Node node) {
Node current = node;
while (current.left != null) {
current = current.left;
}
return(current.data);
}
private int maxValue(Node node) {
Node current = node;
while (current.right != null) {
current = current.right;
}
return(current.data);
}
</code></pre>
<p>I made some edits to the <code>isBST1</code> in my own way, but I'm not sure if there are any flaws in it or not. </p>
<pre><code>static boolean isBST1(BinaryTreeNode root) {
if (root == null) {
return true;
}
if (root.left != null && root.left.value > root.value) {
return false;
}
if (root.right != null && root.right.value < root.value) {
return false;
}
return isBST1(root.left) && isBST1(root.right);
}
</code></pre>
<p>I am wondering if there is any sort of logic I am missing.</p>
|
[] |
[
{
"body": "<p>Here's a simple tree that can demonstrate a couple things:</p>\n\n<pre><code> 5\n / \\\n 3 7\n / \\ \\\n1 6 8\n</code></pre>\n\n<p>minValue and maxValue are written so that the algorithm can catch the 6 that is out of place. And it seems like even the original versions of those functions are not doing that right. Your new algorithm will check the left value (3) and say it's okay, then check the 3-1-6 subtree and also say it's okay, when there's obviously a 6 that is on the left side and that is bigger than the root.</p>\n\n<p>Your new algorithm, however, is broken in the same way as the old algorithm that uses minValue and maxValue is broken, so you translated code with functions into code with no functions \"correctly\" (didn't change anything).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:46:39.180",
"Id": "66216",
"Score": "1",
"body": "This sentence is ambiguous: `Your new algorithm, however, will yield the same results as the old wrong way to find minValue and maxValue, so you got that right` ... is the algorithm right, or wrong? To me it looks like Liondancer's changes are in fact broken, they are wrong, yet you seem to be saying they are working...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:49:06.713",
"Id": "66218",
"Score": "0",
"body": "I've tried my code against a few BST and they seem to be giving me the right results but I'm not sure if I have considered everything"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T20:27:30.903",
"Id": "66221",
"Score": "0",
"body": "@rolfl I'm saying it's broken the same exact way that the old maxValue and minValue functions were broken. I'll edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T20:29:48.723",
"Id": "66222",
"Score": "0",
"body": "@Liondancer Well, try it against my tree and tell us the results!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:24:28.787",
"Id": "66226",
"Score": "0",
"body": "@snetch I tried my code against your tree and i got the wrong value. I built the tree wrong. However, I tried your tree with the method that uses minValue and maxValue and it seems to wrok"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:59:29.513",
"Id": "66235",
"Score": "0",
"body": "Oh, my bad, I misread the original minValue/maxValue example. Never mind, the original functions work correctly."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:07:54.203",
"Id": "39502",
"ParentId": "39500",
"Score": "5"
}
},
{
"body": "<p>Your revised changes to the <code>isBST(Node)</code> method are broken. You only check that all Nodes have a data value that is <code>left < me < right</code>. In other words, you check to make sure that each individual node has appropriate left and right values.</p>\n\n<p>As snetch points out though, the tree:</p>\n\n<pre><code> 5\n / \\\n 3 7\n / \\ \\\n1 6 8\n</code></pre>\n\n<p>is a tree where the node with value <code>6</code> is broken. It should be to the right of the root node <code>5</code>.</p>\n\n<p>Using your logic, the left and right nodes for node <code>5</code> are <em>good</em>, and the left and right nodes for node <code>3</code> are <em>good</em> too. You will declare this tree to be 'good'.</p>\n\n<p>When checking node 5 you should be comparing it on the left side to <code>6</code> and not to <code>3</code> in order to isolate the problem.</p>\n\n<p>In other words, when checking a node, you need to check the maximum value of all its left-sided children against the minimum value of its right-side children.</p>\n\n<p>While the sample code you have uses a recursive process to do that, you can also use a more complicated approach that does a depth-first traversal of the tree, and 'carries' the max (or mmin if you had to go down the right-side) value up from the bottom in order to test the state of the parent node. This method will reduce the scalability complexity from <em>O(n log(n))</em> to <em>O(n)</em></p>\n\n<p>I have taken the liberty of writing a 'carry-up' version of the check which will visit fewer nodes to do the ckck, but will also do a bit more work at each stage to calculate a Min/Max value. The full system, using the same tree as snetch suggested, looks like:</p>\n\n<pre><code>private static class Node {\n private Node left, right;\n private final int value;\n public Node(int val) {\n this.value = val;\n }\n public Node(Node lt, int val, Node rt) {\n this.value = val;\n left = lt;\n right = rt;\n }\n}\n\nprivate static final class MinMax {\n private final int min, max;\n\n public MinMax(int min, int max) {\n super();\n this.min = min;\n this.max = max;\n }\n\n}\n\nprivate static final class NotBSTException extends IllegalStateException {\n private static final long serialVersionUID = 1L;\n}\n\npublic static boolean isBST(Node n) {\n try {\n checkBST(n);\n return true;\n } catch (NotBSTException e) {\n return false;\n }\n}\n\nprivate static MinMax checkBST(final Node n) throws NotBSTException {\n if (n == null) {\n return null;\n }\n MinMax left = checkBST(n.left);\n MinMax right = checkBST(n.right);\n if (left != null && left.max > n.value) {\n throw new NotBSTException();\n }\n if (right != null && right.min < n.value) {\n throw new NotBSTException();\n }\n return new MinMax(left == null ? n.value : left.min, right == null ? n.value : right.max);\n}\n\npublic static void main(String[] args) {\n Node tree = new Node(new Node(new Node(1), 3, new Node(6)), 5, new Node(null, 7, new Node(8)));\n System.out.println(\"3 ->\" + isBST(tree.left));\n System.out.println(\"7 ->\" + isBST(tree.right));\n System.out.println(\"5 ->\" + isBST(tree));\n}\n</code></pre>\n\n<p>And produces the output:</p>\n\n<pre><code>3 ->true\n7 ->true\n5 ->false\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:59:44.287",
"Id": "39509",
"ParentId": "39500",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39509",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:26:11.973",
"Id": "39500",
"Score": "4",
"Tags": [
"java",
"tree",
"binary-search"
],
"Title": "Testing to see if tree is BST"
}
|
39500
|
<p>This is a follow up review of question '<a href="https://codereview.stackexchange.com/questions/39186/a-custom-undo-manager">a custom Undo Manager</a>'.</p>
<p>After reviewing all the comments and answers, my code has been revised (completely rewritten) based on the review. </p>
<p><strong>Summary</strong></p>
<p>The intent of the code is to provide a means to keep track of events in c#. Each Action has an undo and redo event (<code>Command</code>) and is pushed onto a redo or undo <code>Stack<Command></code>. An object can create an instance of the <code>StateManager</code>, which should be private in order keep the undo and redo events encapsulated. For example purposes, I created a class called <code>Car</code>, which has a property of type <code>StateManager</code> which handles all the events. Your comments and suggestions are appreciated. </p>
<pre><code>public interface ICommand
{
// Executes this command.
void Execute();
// Undoes this command.
void Undo();
}
/// <summary>
/// The Command class holds a reference to an Event and the Undo Event
/// </summary>
public class Command:ICommand
{
private readonly Action _action;
private readonly Action _undoAction;
public Command(Action action, Action undoAction)
{
_undoAction = undoAction;
_action = action;
}
public void Execute()
{
_action();
}
public void Undo()
{
_undoAction();
}
}
public interface IStateManager
{
// Executes the specified commmand and adds it to the Undo stack.
void ChangeState(Command commmand);
// Undoes the last command in the Undo stack.
void RestorePreviousState();
// Redoes the last command in the Redo stack.
void RedoPreviousState();
}
public class StateManager:IStateManager
{
private Stack<Command> _undoCommands = new Stack<Command>();
private Stack<Command> _redoCommands = new Stack<Command>();
public void ChangeState(Command command)
{
command.Execute();
_undoCommands.Push(command);
}
public void RestorePreviousState()
{
if (this._undoCommands.Any()) {
var command = _undoCommands.Pop();
command.Undo();
_redoCommands.Clear();// clear the redo stack
_redoCommands.Push(command);// push event on redo stack
}
}
public void RedoPreviousState() {
if (this._redoCommands.Any())
{
var commandPop = this._redoCommands.Pop();
commandPop.Execute();
this._undoCommands.Push(commandPop); // put the event on the undo stack
}
}
}
public class Car
{
/// <summary>
/// StateManager - manages the state of properties/methods that call StateManager.ChangeState.
/// The StateManager is set to private for encapsulated - The State of the object is only handled
/// by the object that instantiates it.
/// </summary>
private StateManager _manager { get; set; }
private String color;
public String Color
{
get { return color; }
set {
string currentValue = color;
_manager.ChangeState(new Command(() => color = value,
() => color = currentValue));
}
}
public Car()
{
_manager = new StateManager();
}
/// <summary>
/// Undo the last event.
/// </summary>
public void Undo() {
_manager.RestorePreviousState();
}
/// <summary>
/// Redo the last event
/// </summary>
public void Redo()
{
_manager.RedoPreviousState();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think you should not clear <code>_redoCommands</code> stack when you are re-doing command. Actually you should be able to continue re-doing command until you will restore state when you called first undo command. You should clear redo-commands when completely new command arrives:</p>\n\n<pre><code>public void ChangeState(Command command)\n{\n command.Execute();\n _undoCommands.Push(command);\n _redoCommands.Clear(); // new command arrived, you cannot redo anymore\n}\n\npublic void RestorePreviousState()\n{\n if (!_undoCommands.Any())\n return;\n\n var command = _undoCommands.Pop();\n command.Undo();\n _redoCommands.Push(command); \n}\n\npublic void RedoPreviousState()\n{\n if (!_redoCommands.Any())\n return;\n\n var command = _redoCommands.Pop(); // commandPop a little strange name :)\n command.Execute();\n _undoCommands.Push(command); \n}\n</code></pre>\n\n<p>Also I'm thinking on improving naming... because <code>RestorePreviousState()</code> looks like restoring state which was before last state change - i.e. two call of this method should leave object in initial state.</p>\n\n<p>UPDATE: I'd go with <code>UndoStateChange</code> and <code>RedoStateChange</code> without word <em>previous</em> - I find such terms less confusing. Also I'd think about making public properties for checking available state changes. Because currently it's not clear whether state changed or not. You call <code>UndoStateChange</code> and nothing is returned whether state changed or there is nothing to undo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:13:59.403",
"Id": "66318",
"Score": "1",
"body": "500 points! Congratulations!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:16:47.167",
"Id": "66319",
"Score": "0",
"body": "@retailcoder thanks :) Nice site, which needs more attention I think (and small design refactoring) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:18:46.530",
"Id": "66320",
"Score": "0",
"body": "The design is because we're still a beta site - we're trying real hard to make 2014 our graduation year! Seen [this](http://meta.codereview.stackexchange.com/questions/1429/sede-is-up-what-now-wonderland?cb=1)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:23:19.687",
"Id": "66322",
"Score": "1",
"body": "@retailcoder nope, I haven't seen that, thanks for link :) Stack Exchange Data Explorer also seems interesting!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:30:16.643",
"Id": "66324",
"Score": "1",
"body": "If, like us (the <s>fanatics</s> *regulars*), you want CR to graduate soon, make sure you check out [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor), this site's main chatroom. Weekends aren't especially busy, but there's always someone in there. And it'll get busier when we resume with [tag:weekend-challenge] :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:00:23.043",
"Id": "39513",
"ParentId": "39503",
"Score": "3"
}
},
{
"body": "<p>The code looks good (apart from _redoCommands.Clear() in the wrong place) but could be a little bit shorter:</p>\n\n<ul>\n<li>Remove the ICommand and IStateManager interfaces (no need for them)</li>\n<li>Making the Action instances public properties of Command would mean you could invoke them directly</li>\n<li>Making StateManager data a public property of Car would mean you could invoke its methods directly ... and returning a new IStateHistory interface would let you let you hide one of the StateManager methods (i.e. the ChangeState method which should only be called from within the Car implementation</li>\n</ul>\n\n<p>For example (altered code, with all your comments removed and my comments added):</p>\n\n<pre><code>public class Command\n{\n // public get and private set is similar to readonly\n public Action Execute { get; private set; }\n public Action Undo { get; private set; }\n public Command(Action action, Action undoAction)\n {\n this.Execute = action;\n this.Undo = undoAction;\n }\n}\n\n// this interface doesn't expose the ChangeState method\npublic interface IStateHistory\n{\n void RestorePreviousState();\n void RedoPreviousState();\n}\n\n// The ChangeState method isn't in the IStateHistory interface,\n// and can be internal instead of public.\npublic class StateManager : IStateHistory\n{\n ... methods of StateManager are as shown in Sergey's answer ...\n}\n\npublic class Car\n{\n private StateManager _manager { get; set; }\n\n private String color;\n\n public String Color\n {\n get { return color; }\n set { \n string currentValue = color;\n _manager.ChangeState(new Command(() => color = value,\n () => color = currentValue)); \n } \n }\n\n public Car()\n {\n _manager = new StateManager();\n }\n\n // Owners of Car instances can call car.StateHistory.RestorePreviousState() and/or\n // call car.StateHistory.RedoPreviousState()\n // but they can't easily the ChangeState method using the IStateHistory interface.\n public IStateHistory StateHistory { get { return StateManager; } }\n\n}\n</code></pre>\n\n<p>An advantage of exposing the <code>public IStateHistory StateHistory</code> property of <code>Car</code>, instead of delegating via methods like <code>public void Redo() { _manager.RedoPreviousState(); }</code> is that there's less to edit if you want to make future changes like the ones which Sergey is suggesting:</p>\n\n<blockquote>\n <p>Also I'd think about making public properties for checking available state changes. Because currently it's not clear whether state changed or not. You call UndoStateChange and nothing is returned whether state changed or there is nothing to undo.</p>\n</blockquote>\n\n<p>You'd make these changes or additions to IStateHistory and StateManager, without needing to edit (add methods or properties to) the Car class.</p>\n\n<hr>\n\n<p><em>Edit to reply to a new question/comment:</em></p>\n\n<blockquote>\n <p>when I changed my Command class to match your example, the behavior change when the 'Action` e.g. this.Execute = action; was set. The event is being executed when Action property is set rather being executed when popped off the stack</p>\n</blockquote>\n\n<p>I ran the following code (as a Console program):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Debug = System.Console;\n\nnamespace Test\n{\n public class Command\n {\n // public get and private set is similar to readonly\n public Action Execute { get; private set; }\n public Action Undo { get; private set; }\n public Command(Action action, Action undoAction)\n {\n Debug.WriteLine(\"Constructing Command\");\n this.Execute = action;\n this.Undo = undoAction;\n Debug.WriteLine(\"Finished constructing Command\");\n }\n }\n\n // this interface doesn't expose the ChangeState method\n public interface IStateHistory\n {\n void RestorePreviousState();\n void RedoPreviousState();\n }\n\n // The ChangeState method isn't in the IStateHistory interface,\n // and can be internal instead of public.\n public class StateManager : IStateHistory\n {\n private Stack<Command> _undoCommands = new Stack<Command>();\n private Stack<Command> _redoCommands = new Stack<Command>();\n public void ChangeState(Command command)\n {\n Debug.WriteLine(\"Invoking ChangeState\");\n command.Execute();\n _undoCommands.Push(command);\n _redoCommands.Clear();\n }\n\n public void RestorePreviousState()\n {\n Debug.WriteLine(\"Invoking RestorePreviousState\");\n if (!_undoCommands.Any())\n return;\n\n var command = _undoCommands.Pop();\n command.Undo();\n _redoCommands.Push(command);\n }\n\n public void RedoPreviousState()\n {\n Debug.WriteLine(\"Invoking RedoPreviousState\");\n if (!_redoCommands.Any())\n return;\n\n var command = _redoCommands.Pop();\n command.Execute();\n _undoCommands.Push(command);\n }\n }\n\n public class Car\n {\n private StateManager _manager { get; set; }\n\n private String color;\n\n public String Color\n {\n get { return color; }\n set\n {\n string currentValue = color;\n _manager.ChangeState(new Command(\n () => { color = value; Debug.WriteLine(\"New value is \" + value); },\n () => { color = currentValue; Debug.WriteLine(\"New value is \" + currentValue); }));\n }\n }\n\n public Car()\n {\n _manager = new StateManager();\n }\n\n // Owners of Car instances can call car.StateHistory.RestorePreviousState() and/or\n // call car.StateHistory.RedoPreviousState()\n // but they can't easily the ChangeState method using the IStateHistory interface.\n public IStateHistory StateHistory { get { return _manager; } }\n\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n Car car = new Car();\n car.Color = \"Blue\";\n car.Color = \"Red\";\n car.StateHistory.RestorePreviousState();\n car.StateHistory.RedoPreviousState();\n }\n }\n}\n</code></pre>\n\n<p>It produces the following output:</p>\n\n<pre><code>Constructing Command\nFinished constructing Command\nInvoking ChangeState\nNew value is Blue\nConstructing Command\nFinished constructing Command\nInvoking ChangeState\nNew value is Red\nInvoking RestorePreviousState\nNew value is Blue\nInvoking RedoPreviousState\nNew value is Red\n</code></pre>\n\n<p>Perhaps I didn't understand your latest question/comment, but IMO the output shows that the action is performed when the StateManager method is called, and not when <code>this.Execute = action;</code> was set inside the Command constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T16:26:23.680",
"Id": "66304",
"Score": "0",
"body": "when I changed my `Command` class to match your example, the behavior change when the 'Action` e.g. `this.Execute = action;` was set. The event is being executed when `Action`property is set rather being executed when popped off the stack"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:08:19.747",
"Id": "66310",
"Score": "1",
"body": "I edited my answer to try to reply to your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T12:40:32.923",
"Id": "66386",
"Score": "0",
"body": "you are correct. When I implemented this code into my bigger project, I introduced a bug, which I thought was caused by the `Command`. - Thank you"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:01:31.667",
"Id": "39517",
"ParentId": "39503",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:17:23.660",
"Id": "39503",
"Score": "3",
"Tags": [
"c#",
"delegates"
],
"Title": "follow-up review of a custom Undo Manager"
}
|
39503
|
<p>I am working on a browser strategy game as a hobby and came up with a decision to use a tile-based map for the world map. </p>
<p>I have several questions so far:</p>
<ul>
<li><p>I am using double-cache (file and apc) for performance issues. Isn't it too much? Or should I consider using Redis or anything similar?</p></li>
<li><p>What would be the best way to add gradients/transition zones to the images I am generating? For example if we have sand surrounded by sea cells, I would like the borders to be smooth between the cells, if you know what I mean :)</p></li>
</ul>
<p>Thanks for any help in advance. Please see below for the code of the MapTile class that I am working on (the rest of the code can be found <a href="https://bitbucket.org/t1gor/strategy/src/4568202177890480e4cc0268b4458889bc6bf0ae?at=default" rel="nofollow">here</a>).</p>
<pre><code><?php
/**
* TODO:
* - add gradients for neighbours tiles
*/
// namespace declaration
namespace Application\Model\Map;
use \PDO;
use \RecursiveDirectoryIterator;
use Application\Core\Cache;
use Application\Model\BaseModel;
use Application\Model\iModel;
use Application\Utils\Registry;
// file access protection
if (!defined('APP_PATH')) exit(_('Access denied'));
class MapTile extends BaseModel implements iModel
{
protected $table = 'map_coords_net';
const CELL_SIZE = 90;
const ZOOM_DEFAULT = 20;
const CACHE_PREFIX_IMG = 'tile_image_';
const CACHE_PREFIX_OBJ = 'tile_object_';
const CACHE_DIRECTORY = 'map/tiles';
public $coordsX = 0;
public $coordsY = 0;
public $mapGroundType = '';
protected $zoom = 0;
protected $image = null;
// neighbours types array for gradient rendering
protected $neighbours = array(
'north' => null,
'south' => null,
'west' => null,
'east' => null,
);
/**
* Get current tile and neighbours (4) details from db
*
* @return void
*/
public function getDetails()
{
// fetch from db
$stmt = $this->db->prepare("
SELECT
self.coordsX,
self.coordsY,
mgt.type as mapGroundType
FROM map_coords_net self
INNER JOIN map_ground_type mgt
ON self.mapGroundType = mgt.mapGroundTypeId
WHERE 1 = 1
-- get self and 5 neighbours if those exist
AND coordsX IN (:coordsX - 1, :coordsX, :coordsX + 1)
AND coordsY IN (:coordsY - 1, :coordsY, :coordsY + 1)
");
$stmt->bindParam(':coordsX', $this->coordsX, PDO::PARAM_INT);
$stmt->bindParam(':coordsY', $this->coordsY, PDO::PARAM_INT);
$stmt->execute();
// fetch request results
$tiles = $stmt->fetchAll(
PDO::FETCH_CLASS,
"\Application\Model\Map\MapTile"
);
// set neighbours array
foreach ($tiles as $tile)
{
// typecast
$tile->coordsX = (int) $tile->coordsX;
$tile->coordsY = (int) $tile->coordsY;
if ($this->equals($tile))
{
// copy tile properties
$this->mapGroundType = $tile->mapGroundType;
}
else {
// fill neignours array
$this->placeNeighbour($tile);
}
}
}
/**
* Get mapGroundTypeId from the `map_ground_type` table
*
* @return int
*/
public static function getMapGroundTypeByName($groundTypeName)
{
$groundTypeName = trim($groundTypeName);
$stmt = Registry::get('db')->prepare("
SELECT mapGroundTypeId
FROM map_ground_type
WHERE type = :type
");
$stmt->bindParam(':type', $groundTypeName, PDO::PARAM_STR);
$stmt->execute();
return (int) $stmt->fetchColumn();
}
/**
* Place neighbour in the corresponding array element
*
* @param MapTile $tile
*
* @return void
*/
protected function placeNeighbour(MapTile $tile)
{
if ($this->coordsX == $tile->coordsX - 1)
{
$this->neighbours['north'] = $tile;
}
if ($this->coordsX == $tile->coordsX + 1)
{
$this->neighbours['south'] = $tile;
}
if ($this->coordsY == $tile->coordsY - 1)
{
$this->neighbours['west'] = $tile;
}
if ($this->coordsY == $tile->coordsY + 1)
{
$this->neighbours['east'] = $tile;
}
}
/**
* Compare the passed tile to this one
*
* @param MapTile $tile
* @param string $compareBy - comparison method
*
* @return bool
*/
protected function equals(MapTile $tile, $compareBy = 'coords')
{
switch ($compareBy)
{
default:
case 'coords':
// return comapre results
return (
$this->coordsX == $tile->coordsX
&& $this->coordsY == $tile->coordsY
);
break;
}
return false;
}
/**
* Set tile coords
*
* @param int $x
* @param int $y
* @param int $z
*
* @return void
*/
public function setCoords($x, $y, $z = 20)
{
$this->coordsX = (int) $x;
$this->coordsY = (int) $y;
$this->zoom = (int) $z;
$this->getDetails();
}
/**
* Set image header for the output
*
* @return void
*/
public static function setImageHeader()
{
$cacheLifeTime = Cache::DEFAULT_TTL;
$ts = gmdate("D, d M Y H:i:s", time() + $cacheLifeTime) . " GMT";
header("Expires: {$ts}");
header("Pragma: cache");
header("Cache-Control: max-age={$cacheLifeTime}");
header('Content-type: image/jpeg');
}
/**
* Create image object
*
* Double-cached in files and apc
*
* @return void
*/
public function render()
{
$cacheKey = self::CACHE_PREFIX_IMG.$this->coordsX.':'.$this->coordsY;
$cacheFilePath = CACHE_PATH.self::CACHE_DIRECTORY.DIRECTORY_SEPARATOR.$cacheKey.'.jpg';
$id = array(
'coordsX' => $this->coordsX,
'coordsY' => $this->coordsY,
);
self::setImageHeader();
// check if cached file exists
if (file_exists($cacheFilePath))
{
if (Cache::exists($cacheKey)) {
$imageContent = unserialize(Cache::get($cacheKey));
}
else {
// get from file
$imageContent = file_get_contents($cacheFilePath);
// save in apc
Cache::set($cacheKey, serialize($imageContent));
}
// show file contents
echo $imageContent;
return;
}
// or create an image
else {
// create image object
$this->image = ImageCreateTrueColor(self::CELL_SIZE, self::CELL_SIZE);
if ($this->exists($id))
{
switch ($this->mapGroundType)
{
default:
case 'sea':
$backgroundColor = array_map('hexdec', str_split('0099FF', 2));
$noizeColor = array_map('hexdec', str_split('004C80', 2));
break;
case 'stone':
case 'mountain':
$backgroundColor = array_map('hexdec', str_split('969BA0', 2));
$noizeColor = array_map('hexdec', str_split('5A5D60', 2));
break;
case 'sand':
$backgroundColor = array_map('hexdec', str_split('CC9900', 2));
$noizeColor = array_map('hexdec', str_split('996600', 2));
break;
case 'forest':
$backgroundColor = array_map('hexdec', str_split('336600', 2));
$noizeColor = array_map('hexdec', str_split('003300', 2));
break;
case 'grass':
$backgroundColor = array_map('hexdec', str_split('339933', 2));
$noizeColor = array_map('hexdec', str_split('006600', 2));
break;
}
// create colors from RGB
$backgroundColorRGB = ImageColorAllocate($this->image, $backgroundColor[0], $backgroundColor[1], $backgroundColor[2]);
$noizeColorRGB = ImageColorAllocate($this->image, $noizeColor[0], $noizeColor[1], $noizeColor[2]);
// add noize
for ($w = 0; $w <= self::CELL_SIZE; $w++)
{
for ($h = 0; $h <= self::CELL_SIZE; $h++)
{
if (mt_rand(1, 100) >= 30) {
ImageSetPixel($this->image, $w, $h, $backgroundColorRGB);
}
else {
ImageSetPixel($this->image, $w, $h, $noizeColorRGB);
}
}
}
// black text for couloured tiles
$textcolor = ImageColorAllocate($this->image, 0, 0, 0);
}
else {
// display black rectangle for non-existing tile
$backgroundColorRGB = imagecolorallocate($this->image, 0, 0, 0);
imagefilledrectangle($this->image, 0, 0,
self::CELL_SIZE, self::CELL_SIZE,
$backgroundColorRGB
);
// white text for couloured tiles
$textcolor = ImageColorAllocate($this->image, 255, 255, 255);
}
}
// set text
$coordsString = "{$this->coordsX}:{$this->coordsY}";
ImageString($this->image, 1, 5, 5, $coordsString, $textcolor);
// save to cache
ImageJpeg($this->image, $cacheFilePath);
// view
ImageJpeg($this->image);
ImageDestroy($this->image);
}
/**
* Clear tile cache, saved in files
*
* @return bool
*
*/
public static function flushFileCache()
{
$tiles = new RecursiveDirectoryIterator(CACHE_PATH.self::CACHE_DIRECTORY);
foreach ($tiles as $fileInfo) {
unlink($fileInfo->getRealPath());
}
return true;
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T08:56:50.223",
"Id": "66638",
"Score": "0",
"body": "Given they are tiles, is it possible to pre-render all the tiles including the variations, sand-to-sea, sand-to-forest etc, then just return the correct url of the tile? This way you could use a cdn to cache the tiles for you. (Obviously this would depend on the complexity of the tiles, and i have only just skimmed over the code base)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T10:03:04.530",
"Id": "66643",
"Score": "0",
"body": "I am pre-rendering and caching the tile files already. But even on localhost it seems to be slow. I will publish the code somewhere shortly and will post a link to check/test. Thanks for an effort, anyway :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T01:26:19.887",
"Id": "66730",
"Score": "0",
"body": "If it is slow on localhost, then you might have some issues in the real world.. Have you isolated where the slow is, eg database, tile generation, network issue, cpu? I know php isn't the best language for image processing have you tried imagick vs gd for image processing. Not sure if you are using apache, but mod x-sendfile could help offload some of the work from php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T14:43:10.133",
"Id": "66779",
"Score": "0",
"body": "@bumperbox, I considered switching to `imagick`, but this project will most probably be started from the shared hosting environment, which is why I decided not to use the one. Could you please give me a hint on what `mod x-sendfile` is?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T20:09:40.020",
"Id": "66830",
"Score": "0",
"body": "x-sendfile just allows you to offload files to apache. Rather then keeping a php script running just to return the file. I use it for larger files, pdf's etc, I am not sure of the performance gain you would get from small tiles. If you are using shared hosting, it is most likely you wont have access to this module anyway"
}
] |
[
{
"body": "<p>I had a look through the code, if it runs slow then it is most likely a network issue from what I can tell.</p>\n\n<p>I think you are caching the wrong thing. </p>\n\n<p>A better solution might be to change the design of the tiles and remove the coordinates from them.</p>\n\n<p>You have 6 types of tiles Sea, sTone, Mountain, sanD, Forest, Grass</p>\n\n<p>First up, pre-render all six tiles \nS.jpg\nT.jpg\nM.jpg\nD.jpg\nF.jpg\nG.jpg</p>\n\n<p>Next render all the possible combos and combos of tiles eg sea/sand etc, naming them in centre-north-east-south-west naming convention.</p>\n\n<p>SSDSS.jpg would be Sea surrounded by sea (north), sand (east), sea (south), sea (west)</p>\n\n<p>Next is the game loop</p>\n\n<ul>\n<li>A request comes in for a tile at coords x,y</li>\n<li>Perform a database query to find the neighbours </li>\n<li>From the neighbours lookup you should be able to build a filename, eg SSDSS.jpg</li>\n<li>Cache the tile name against the coordinates to save us any further database lookup</li>\n<li>header('Location: <a href=\"http://cdn.mygame.com/tiles/SSDSS.jpg\" rel=\"nofollow\">http://cdn.mygame.com/tiles/SSDSS.jpg</a>');</li>\n</ul>\n\n<p>This way the browser does the img caching not your server, so the network bottleneck is no longer an issue. There are a limited number of combinations that the browser needs to cache.</p>\n\n<p>I am making some big assumptions about your design here</p>\n\n<p>If you treat the tile as a div background, you can use plain html to render the coords over every tile if required.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T01:20:20.050",
"Id": "66855",
"Score": "0",
"body": "Good thinking, and it is worth re-iterating, that the browser should be treated as part of a massive computational cluster. The more you push to the browser the better, and especially when there are multiple browsers using one server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T12:36:23.510",
"Id": "66900",
"Score": "0",
"body": "@bumperbox, thanks for the suggestion. BTW - I am setting browser cache headers - isn't it enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T12:46:22.377",
"Id": "66903",
"Score": "0",
"body": "Regarding the combos - I will have a bit more complicated structute (corners also count), so it will be 8 nighbours. I already started here: https://bitbucket.org/t1gor/strategy/src/242e58cdcd60c61d02ae26d420da9d415117cb0d/application/model/map/MapTile.php?at=default#cl-133. Anyway, the idea is clear and I will try that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T19:30:38.433",
"Id": "66957",
"Score": "1",
"body": "@t1gor your caching headers are fine. The main point is that because each tile has the coordinates rendered on it they are all unique. If you have a 100x100 grid, then your app will need to generate 10,000 unique jpgs. That is a lot of images, far more then if you used a set of common images."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T01:05:45.530",
"Id": "39849",
"ParentId": "39505",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39849",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:35:41.320",
"Id": "39505",
"Score": "2",
"Tags": [
"php",
"game",
"image"
],
"Title": "Game map tiles generation with php"
}
|
39505
|
<p>So I've got this module called risar, which draws. But that's not really of importance. I wrote this code which sets 20 flowers on the background.</p>
<p>Now they need to move downwards by 5 units. The code works fine but it looks horribly awkward to me. I'd like it to look more "fancy" or maybe that less loops would be used or I'd like to see simply another way to do it. I need help with 2nd function; the 1st one looks okay. I'm relatively new to Python.</p>
<pre><code>def doFlowers():
flowers = []
colors = ["black_flower.svg","blue_flower.svg", "brown_flower.svg", "green_flower.svg","purple_flower.svg"]
for i in range(20):
x = random.randint(20, (risar.maxX-20))
y = random.randint(20, 300)
flower = risar.picture(x, y, barve[i//4]) # 0, 1, 2, 3, 4
flowers.append(flower)
return flowers
flowers = doFlower()
def moving(flower):
for i in range(len(flower)):
while flower[i].y() < risar.maxY:
for p in flower: #p is position
p.setPos(p.x(), p.y()+5)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:19:28.093",
"Id": "66225",
"Score": "0",
"body": "So moving is supposed to animate the drawing by moving flowers every frame?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:49:58.687",
"Id": "66256",
"Score": "0",
"body": "You probably mean `flowers = doFlowers()`."
}
] |
[
{
"body": "<p>Let's start with your naming. <code>flower</code> is supposed to be a list, right? Let's make it plural, then.</p>\n\n<pre><code>def moving(flowers):\n for i in range(len(flowers)):\n while flowers[i].y() < risar.maxY:\n for p in flowers: #p is position\n p.setPos(p.x(), p.y()+5)\n</code></pre>\n\n<p>Next, notice that you don't actually care about <code>i</code>; you just want to operate on every single flower.</p>\n\n<pre><code>def moving(flowers):\n for f in flowers:\n while f.y() < risar.maxY:\n for p in flowers: #p is position\n p.setPos(p.x(), p.y()+5)\n</code></pre>\n\n<p>Hmm… not only are there nested loops, but two of them iterate over all flowers. What's going on? I think you're trying to move all flowers \"simultaneously\" until all of them have their y-coordinate ≥ <code>risar.maxY</code>. Then just say this, which I think is a bit more expressive:</p>\n\n<pre><code>def moving(flowers):\n while any([f.y() < risar.maxY for f in flowers]):\n for flower in flowers:\n flower.setPos(flower.x(), flower.y() + 5)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:49:18.873",
"Id": "39522",
"ParentId": "39506",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39522",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:39:08.267",
"Id": "39506",
"Score": "3",
"Tags": [
"python",
"beginner",
"iteration"
],
"Title": "Drawing and moving flowers"
}
|
39506
|
<p>I am trying to make a 3D application with OpenGL/LWJGL at the moment, but I am now already hitting some limits on the JVM, most likely due to a configuration that needs to be done.</p>
<p>I have the following code in the render loop:</p>
<pre><code>@Override
protected void render(final double msDelta) {
glClearColor(0.0f, 0.25f, 0.0f, 1.0f);
glClearDepthf(1f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
testProgram.use();
for (int i = 0; i < 2400; i++) {
float fVar = i + currentTime / 1000f * 0.3f;
modelviewMatrix = Matrix4f.multiply(
Matrix4f.translate(0.0f, 0.0f, -8.0f), //translate
Matrix4f.rotate(currentTime / 1000f * 45.0f, 0.0f, 1.0f, 0.0f), //rotate around Y
Matrix4f.rotate(currentTime / 1000f * 21.0f, 1.0f, 0.0f, 0.0f), //rotate around X
Matrix4f.translate(
(float)Math.sin(2.1f * fVar) * 2.0f,
(float)Math.cos(1.7f * fVar) * 2.0f,
(float)Math.sin(1.3f * fVar) * (float)Math.cos(1.5f * fVar) * 2.0f
) //translate
);
glUniformMatrix4(MODELVIEW_LOCATION, false, modelviewMatrix.asFloatBuffer());
glDrawArrays(GL_TRIANGLES, 0, 36);
}
}
</code></pre>
<p>The most important part is <code>Matrix4f</code> (My own implementation, not LWJGL's one... I don't know how I could make it more clear without renaming it to something terrible):</p>
<pre><code>public class Matrix4f {
private final static float EPSILON = 0.01f;
private final float[] elements = new float[16];
public Matrix4f() {
}
public Matrix4f(final float[] elements) {
System.arraycopy(elements, 0, this.elements, 0, 16);
}
public Matrix4f multiply(final Matrix4f other) {
float[] a = getElements();
float[] b = other.getElements();
return new Matrix4f(new float[] {
a[0] * b[0] + a[4] * b[1] + a[8] * b[2] + a[12] * b[3],
a[1] * b[0] + a[5] * b[1] + a[9] * b[2] + a[13] * b[3],
a[2] * b[0] + a[6] * b[1] + a[10] * b[2] + a[14] * b[3],
a[3] * b[0] + a[7] * b[1] + a[11] * b[2] + a[15] * b[3], //X column
a[0] * b[4] + a[4] * b[5] + a[8] * b[6] + a[12] * b[7],
a[1] * b[4] + a[5] * b[5] + a[9] * b[6] + a[13] * b[7],
a[2] * b[4] + a[6] * b[5] + a[10] * b[6] + a[14] * b[7],
a[3] * b[4] + a[7] * b[5] + a[11] * b[6] + a[15] * b[7], //Y column
a[0] * b[8] + a[4] * b[9] + a[8] * b[10] + a[12] * b[11],
a[1] * b[8] + a[5] * b[9] + a[9] * b[10] + a[13] * b[11],
a[2] * b[8] + a[6] * b[9] + a[10] * b[10] + a[14] * b[11],
a[3] * b[8] + a[7] * b[9] + a[11] * b[10] + a[15] * b[11], //Z column
a[0] * b[12] + a[4] * b[13] + a[8] * b[14] + a[12] * b[15],
a[1] * b[12] + a[5] * b[13] + a[9] * b[14] + a[13] * b[15],
a[2] * b[12] + a[6] * b[13] + a[10] * b[14] + a[14] * b[15],
a[3] * b[12] + a[7] * b[13] + a[11] * b[14] + a[15] * b[15] //W column
});
}
public FloatBuffer asFloatBuffer() {
FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(elements.length).put(elements);
floatBuffer.flip();
return floatBuffer;
}
float[] getElements() {
return elements;
}
@Override
public String toString() {
return Arrays.toString(elements);
}
public static Matrix4f identity() {
return new Matrix4f(new float[] {
1.0f, 0.0f, 0.0f, 0.0f, //X column
0.0f, 1.0f, 0.0f, 0.0f, //Y column
0.0f, 0.0f, 1.0f, 0.0f, //Z column
0.0f, 0.0f, 0.0f, 1.0f //W column
});
}
public static Matrix4f scale(final float sx, final float sy, final float sz) {
return new Matrix4f(new float[] {
sx, 0.0f, 0.0f, 0.0f, //X column
0.0f, sy, 0.0f, 0.0f, //Y column
0.0f, 0.0f, sz, 0.0f, //Z column
0.0f, 0.0f, 0.0f, 1.0f //W column
});
}
public static Matrix4f translate(final float tx, final float ty, final float tz) {
return new Matrix4f(new float[] {
1.0f, 0.0f, 0.0f, 0.0f, //X column
0.0f, 1.0f, 0.0f, 0.0f, //Y column
0.0f, 0.0f, 1.0f, 0.0f, //Z column
tx, ty, tz, 1.0f //W column
});
}
public static Matrix4f rotate(final float theta, final float x, final float y, final float z) {
if (Math.abs(x * x + y * y + z * z - 1.0f) >= EPSILON) {
throw new IllegalArgumentException("(x, y, z) is not a unit vector: x = " + x + ", y = " + y + ", z = " + z);
}
float thetaRad = (float)Math.toRadians(theta);
float cosTheta = (float)Math.cos(thetaRad);
float sinTheta = (float)Math.sin(thetaRad);
float cosThetaRes = 1.0f - cosTheta;
return new Matrix4f(new float[] {
cosTheta + x * x * cosThetaRes, y * x * cosThetaRes + z * sinTheta, z * x * cosThetaRes - y * sinTheta, 0.0f, //X column
x * y * cosThetaRes - z * sinTheta, cosTheta + y * y * cosThetaRes, z * y * cosThetaRes + x * sinTheta, 0.0f, //Y column
x * z * cosThetaRes + y * sinTheta, y * z * cosThetaRes - x * sinTheta, cosTheta + z * z * cosThetaRes, 0.0f, //Z column
0.0f, 0.0f, 0.0f, 1.0f //W column
});
}
public static Matrix4f frustum(final float left, final float right, final float bottom, final float top, final float near, final float far) {
return new Matrix4f(new float[] {
2 * near / (right - left), 0.0f, 0.0f, 0.0f, //X column
0.0f, 2 * near / (top - bottom), 0.0f, 0.0f, //Y column
(right + left) / (right - left), (top + bottom) / (top - bottom), (near + far) / (near - far), -1.0f, //Z column
0.0f, 0.0f, 2 * near * far / (near - far), 0.0f //Z column
});
}
public static Matrix4f perspective(final float fovy, final float aspect, final float near, final float far) {
float y2 = near * (float)Math.tan(Math.toRadians(fovy * 0.5f));
float y1 = -y2;
float x1 = y1 * aspect;
float x2 = y2 * aspect;
return frustum(x1, x2, y1, y2, near, far);
}
public static Matrix4f multiply(final Matrix4f... matrices) {
Matrix4f output = identity();
for (Matrix4f matrix : matrices) {
output = output.multiply(matrix);
}
return output;
}
}
</code></pre>
<p>As far as I see everything is method specific (a local variable) and thus eligible for garbage collection.</p>
<p>I have the following questions:</p>
<ul>
<li>Did I overlook something, resulting in it to not be garbage collected?</li>
<li>Could some parts be done faster?</li>
<li>Most importantly: With what garbage collector settings should I play to make it garbage collect all local variables as fast as possible, without doing a Stop-The-World garbage collect?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:30:10.217",
"Id": "66230",
"Score": "0",
"body": "Your render method should not compile given the class Matrix4f you have shown. Could you show a compilable example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T03:09:15.943",
"Id": "66261",
"Score": "2",
"body": "You should make your conventions clear. The constructor should have JavaDoc that says that `elements` is in column-major order. Also name the argument `multiply(Matrix4f right)` to clarify which matrix is on the right side of the multiplication."
}
] |
[
{
"body": "<p>Not that may be your issue but I would do your multiply algorithm with a loop:</p>\n\n<pre><code>public Matrix4f multiply(final Matrix4f other) {\n float[] a = getElements();\n float[] b = other.getElements();\n float[] result = new float[a.length];\n //assume a.length == b.length and that lines * columns = a.length\n int alen = Math.sqrt(a.length);\n for(int l = 0; l < alen; ++l){\n for(int c = 0; c < alen; ++c){\n int res = 0;\n for(int k = 0; k < alen; ++k){\n res += a[c*alen +k] * b[l*alen +k]\n }\n result[l*alen + c] = res;\n }\n\n }\n result new Matrix4f(result);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:19:01.420",
"Id": "39514",
"ParentId": "39508",
"Score": "1"
}
},
{
"body": "<p>modelviewMatrix is not available for garbage collection until the render() method is complete. It is not clear from the code where this variable is actually defined and why it is not declared in the render() method.</p>\n\n<p>My suggestion is to move the code inside the for loop into its own method, lets call it renderIteration. Any objects created in the renderIteration() method and not returned to the caller will be available for GC when the renderIteration() method completes.</p>\n\n<p>Cheers. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:31:58.173",
"Id": "39516",
"ParentId": "39508",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39516",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:53:53.347",
"Id": "39508",
"Score": "5",
"Tags": [
"java",
"matrix",
"floating-point",
"opengl",
"garbage-collection"
],
"Title": "Optimizing garbage collection for local objects"
}
|
39508
|
<p>I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.</p>
<p>If you are unfamiliar with Unity3d, ignore the use of <code>UnityEngine</code>, the heritage from <code>MonoBehaviour</code> as well as the <code>Debug.Log()</code>, <code>Debug.LogWarning()</code>, and <code>Debug.LogError()</code>.</p>
<p><a href="https://codereview.stackexchange.com/questions/39475/inventory-script-rpg-in-c">Inventory Script (RPG) in C#</a></p>
<p>This is an updated version of the inventory code from there, nothing in that question is needed for this.</p>
<pre><code>using UnityEngine;
public class Party : MonoBehaviour {
//private MemberCharacter[] members;
private Item[] inventory;
private int _currency;
public const int INVENTORY_SIZE = 50; // will be changed later to 50*party members
public Party () {
inventory = new Item[INVENTORY_SIZE];
}
// add q items
// first stack in existing items
// then make new slot
// if there is no place it returns the overflow
public int AddItem (Item item, int q) {
// stores items left
int tRemain = q;
// checks if the item already exist in inventory
// adding to its stack
int idxFree = FirstFreeSlot();
for (int i = 0; i < inventory.Length; ++i) {
Item tItem = inventory[i];
if (tItem == item && tItem.MaxQuantity > tItem.Quantity) {
// gets MaxQuantity - Quantity - q (remaining stacks left)
tRemain = inventory[i].Add(q);
// no stacks of item left
if(tRemain == 0) {
Debug.Log ("All " + q + "x " + item.Name + " added.");
return 0;
}
}
}
// is there a free slot?
while (idxFree >= 0) {
// create new items and remove from tRemain
inventory[idxFree] = item;
tRemain = inventory[idxFree].Add (tRemain);
// any remaining items?
if(tRemain == 0) {
Debug.Log ("All " + q + "x " + item.Name + " added.");
return 0;
}
// checking for another slot
idxFree = FirstFreeSlot();
}
// no free slots
// returns items in stack left
Debug.LogWarning ("Inventory full! " + q + "x " + item.Name + " left.");
return tRemain;
}
// swaps items in two slots
public void Move (int src, int dst) {
Item tItem = inventory[dst];
inventory [dst] = inventory [src];
inventory [src] = tItem;
}
// remove q items at i
// check when calling function to make sure q is greater than or equal to ItemSlot[i].quanity
public void RemoveItem (int i, int q) {
// removed too many!
if(inventory[i].Remove(q) == false){
Debug.LogError ("Quantity at index " + i + " is " + inventory[i].Quantity + "!");
DeleteItem (i);
}
// removed all? delete item at i
if (inventory [i].Quantity == 0) {
Debug.Log ("Deleted " + inventory[i].Name);
DeleteItem (i);
}
}
// item at i has a q of 0, delete item
private void DeleteItem (int i) {
inventory [i] = null;
}
// finds a free slot, returns -1 when no slot is present
private int FirstFreeSlot(){
for(int i = 0; i < inventory.Length; ++i){
if(inventory[i] == null)
return i;
}
return -1;
}
// checks if q items exists in inventory
// returns the number of missing items
// 0 item and quantity are met
// -1 item is not met
public int FindItem (Item item, int q) {
return -1;
}
#region Setters and Getters
public int Currency {
get {return _currency;}
set {_currency = value;}
}
#endregion
}
</code></pre>
<p>Item Class:</p>
<pre><code>using UnityEngine;
public class Item : MonoBehaviour {
private string _name;
private string _desc;
private int _quantity;
private int _maxQuantity;
private int _category;
private bool _dropable;
private int _price;
public Item () {
_name = string.Empty;
_desc = string.Empty;
_quantity = 0;
_maxQuantity = 0;
_category = 0;
_dropable = false;
_price = 0;
}
// returns the quatity left to add
// returns 0 when there are no more items
public int Add(int q){
// does q fit into _quantity?
if (q + _quantity <= _maxQuantity) {
Debug.Log ("Added to existing item in one stack " + q + "x " + _name);
_quantity += q;
return 0;
}
// need more slots than 1 add as many as possible
// returns what is left of q
int tRemain = _maxQuantity - _quantity;
Debug.Log("Added " + tRemain + "x " + _name + " - " + q + " left.");
q -= tRemain;
_quantity = _maxQuantity;
return q;
}
// remove items from quantity
// returns true if _quantity > 0 after execution
public bool Remove (int q){
if(_quantity >= q){
_quantity -= q;
Debug.Log ("Removed " + q + "x " + _name);
return true;
}
// can't remove this many!
return false;
}
#region Setters and Getters
public string Name {
get {return _name;}
set {_name = value;}
}
public string Desc {
get {return _desc;}
set {_desc = value;}
}
public int Quantity {
get {return _quantity;}
set {_quantity = value;}
}
public int MaxQuantity {
get {return _maxQuantity;}
set {_maxQuantity = value;}
}
public int Category {
get {return _category;}
set {_category = value;}
}
public bool Dropable {
get {return _dropable;}
set {_dropable = value;}
}
public int Price {
get {return _price;}
set {_price = value;}
}
#endregion
}
// enum used to identify categories by name
public enum ItemCategory {
Miscellaneous,
Quest,
Consumable,
Weapon,
Armor,
Gem,
Resource,
};
</code></pre>
<p>I know you aren't supposed to have two questions in one question but I take it I should probably make a singleton <code>Inventory</code> class to mange the inventory now?</p>
|
[] |
[
{
"body": "<p>Here is a bug:</p>\n\n<pre><code>int tRemain = q;\n\nfor (...)\n if (...)\n tRemain = inventory[i].Add(q);\n</code></pre>\n\n<p>I think the above should be <code>tRemain = inventory[i].Add(tRemain);</code>.</p>\n\n<p>I don't see why you have <code>tRemain</code> as an extra/new variable, instead of just using q.</p>\n\n<pre><code> q = inventory[i].Add(q);\n</code></pre>\n\n<p>Here is how I would code the AddItems method:</p>\n\n<pre><code>public int AddItem (Item item, int q) {\n\n // no because it's confusing to have more than one varable\n //int tRemain = q;\n\n // no because we're about the iterate the array anyway\n //int idxFree = FirstFreeSlot();\n\n for (int i = 0; i < inventory.Length; ++i) {\n\n Item tItem = inventory[i];\n\n // no need to check tItem.MaxQuantity because it's checked inside Item.Add\n //if (tItem == item && tItem.MaxQuantity > tItem.Quantity) {\n\n if (tItem == item) {\n\n // gets MaxQuantity - Quantity - q (remaining stacks left)\n q = inventory[i].Add(q);\n\n // no stacks of item left\n if(q == 0) {\n Debug.Log (\"All \" + q + \"x \" + item.Name + \" added.\");\n return 0;\n }\n }\n\n if (tItem == null) {\n // code which used to be after the for loop\n\n // no because we're already in a for loop and at the right index\n //while (idxFree >= 0)\n inventory[i] = item;\n q = inventory[i].Add(q);\n\n // any remaining items?\n if(q == 0) {\n Debug.Log (\"All \" + q + \"x \" + item.Name + \" added.\");\n return 0;\n }\n\n // no because we're already in a for loop and at the right index\n //idxFree = FirstFreeSlot();\n }\n }\n\n // no free slots\n // returns items in stack left\n Debug.LogWarning (\"Inventory full! \" + q + \"x \" + item.Name + \" left.\");\n return q;\n}\n</code></pre>\n\n<p>I think there's another bug in your architecture: which is that when an Item instance is full then you put the same Item instance into the next slot. If the Item is full in one slot, then the same Item instance is full in the next slot.</p>\n\n<p>With your existing architecture you can't store an Item in more than one slot, if you have more than maxQuantity of that item, which you seem to be trying to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:26:11.130",
"Id": "66236",
"Score": "0",
"body": "I use it for Debug.Log() currently. I don't see the supposed error. I don't get any warnings of any sort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:40:36.363",
"Id": "66241",
"Score": "0",
"body": "For example if q is 3 to begin with, and you find an slot that accepts 2, then tRemain is 1. Then the next time through the for loop you might find another partially-empty slot: if so then you add q (i.e. 3) again, instead of adding tRemain (i.e. 1). You will go through the for loop again because you don't `break;` when you find the first match. There may be more than one matching non-filled slot because your RemoveItem method allows you to remove quantities from any slot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:42:59.077",
"Id": "66243",
"Score": "0",
"body": "Oh yes. That forces me to use another variable for the debugging. Silly me, I will update the post with q for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:17:38.183",
"Id": "66250",
"Score": "0",
"body": "@Emz I think after that fix you can follow up your progress for a while now. I wouldn't make any major changes to your code. Show a bit effort and only post other question (if you want to) after making some progress. Don't forget to run and debug your code before posting a code review or ask a question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:22:37.447",
"Id": "66252",
"Score": "0",
"body": "@Emz I edited my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:27:28.380",
"Id": "66253",
"Score": "0",
"body": "Problem with that is let's say inventory[3] and inventory[12] both hold the same item, none of them have their Quantity == MaxQuantity. So I need to go through and add to all existing items first, then if something remains I will go ahead and place it in the empty slots. I also need to check when storing the item into an empty slot that the items MaxQuantity is less than Quantity, in theory one could AddItem(SuperItem, 25000000) no item will be able to stack to that many, so I have to go over and subtract from it and let the script handle it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:34:22.680",
"Id": "66254",
"Score": "0",
"body": "@Emz If they hold the same Item instance, then that Item instance has the same Item._quantity in both slots. Do you know C++? In C# an Item is like a C++ 'reference' or pointer. If two Items are the same (see e.g. `if (tItem == item)` and `inventory[idxFree] = item;`) then they contain the same data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:36:41.560",
"Id": "66255",
"Score": "0",
"body": "I forgot to say to him in my previous post that maybe he forgot to implement the == operator (or equals instead). However if it is supposed to be a Refrence.Equals check then you're absolutly right"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:23:11.910",
"Id": "39520",
"ParentId": "39510",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39520",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T20:05:50.183",
"Id": "39510",
"Score": "2",
"Tags": [
"c#",
"unity3d"
],
"Title": "Follow Up Inventory Script (RPG) in C#"
}
|
39510
|
<p>I have a click event that calls a function (below, txtResize) which makes some CSS changes to html text. (Acts on Text of 3 unique elements).</p>
<p>Q: What is the best way to refactor this code to limit excessive if/else usage, AND restore the original state of ALL text elements once the user clicks away from this section?</p>
<p>Here is the partially working, ugly function: </p>
<pre><code> function txtResize() {
var clicked = this.id;
if (clicked == "Text1")
{
$("#" + clicked).css("opacity", "1");
$("#Text2, #Text3").css("opacity", "0.2");
}
else if (clicked == "Text2")
{
$("#" + clicked).css("opacity", "1");
$("#Text1, #Text3").css("opacity", "0.2");
}
else if (clicked == "Text3")
{
$("#" + clicked).css("opacity", "1");
$("#Text1, #Text2").css("opacity", "0.2");
}
// code above is ok, below does not work
else if ( !(clicked == "Text1") && !(clicked == "Text2") && !(clicked == "Text3") )
{
$("#Text1, #Text2, #Text3").css("opacity", "1"); // return to default state
}
};
</code></pre>
|
[] |
[
{
"body": "<p>This is actually a pretty classic problem and I've addressed it in my code on numerous occasions. One of the simplest ways to do what you're doing is to just reset the state for all the elements and then correct it.</p>\n\n<pre><code>function txtResize() {\n var clicked = this.id;\n\n if ( clicked === \"Text1\" || clicked === \"Text2\" || clicked === \"Text3\" ) { //one of our text's were clicked\n $(\"#Text1, #Text2, #Text3\").css(\"opacity\", \"0.2\"); //reset them all to .2 opacity\n $(this).css(\"opacity\", \"1\");//set this elements opacity to full\n } else { //its clearly not Text1/2/3\n $(\"#Text1, #Text2, #Text3\").css(\"opacity\", \"1\"); // return to default state\n }\n };\n</code></pre>\n\n<p>One nit-picky point is that we tend to prefer lower case in attributes for html. I would recommend <code>text1</code>, <code>text2</code>... or even better would be to give an id that better described what the element is on the page.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T21:35:35.187",
"Id": "66569",
"Score": "0",
"body": "Thanks mega, couple issues: using $(this) doesn't work for me, but replace it with $(\"#\" + clicked) will. Also, the opacity does not automatically restore itself, I still need to explicitly call another function to get the opacity to return."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T00:20:13.020",
"Id": "66588",
"Score": "0",
"body": "I'd be interested in seeing an example where `$(this)` doesn't wrap the same element as `$(\"#\" + this.id)`. Do you have multiple elements with the same id on your page (quite a poor practice)? If you'd set up a jsfiddle or jsbin I'd play around with the code some more"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:19:10.937",
"Id": "39519",
"ParentId": "39512",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T20:52:18.277",
"Id": "39512",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Changing html element with click event: how to restore default state of element using jQuery if/else statement"
}
|
39512
|
<p>Are there any improvements to these two classes which implement <a href="http://www.isthe.com/chongo/tech/comp/fnv/index.html" rel="nofollow">FNV-1a</a> for hashing? Particularly, I'm looking for any reuse opportunities (possibly via a common abstract superclass derived from <code>HashAlgorithm</code>?).</p>
<p><a href="https://github.com/jslicer/FNV-1a/" rel="nofollow">GitHub</a></p>
<pre><code>public sealed class Fnv1a32 : HashAlgorithm
{
private const uint FnvPrime = unchecked(16777619);
private const uint FnvOffsetBasis = unchecked(2166136261);
private uint hash;
public Fnv1a32()
{
this.Reset();
}
public override void Initialize()
{
this.Reset();
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
for (var i = ibStart; i < cbSize; i++)
{
unchecked
{
this.hash ^= array[i];
this.hash *= FnvPrime;
}
}
}
protected override byte[] HashFinal()
{
return BitConverter.GetBytes(this.hash);
}
private void Reset()
{
this.hash = FnvOffsetBasis;
}
}
</code></pre>
<p>and</p>
<pre><code>public sealed class Fnv1a64 : HashAlgorithm
{
private const ulong FnvPrime = unchecked(1099511628211);
private const ulong FnvOffsetBasis = unchecked(14695981039346656037);
private ulong hash;
public Fnv1a64()
{
this.Reset();
}
public override void Initialize()
{
this.Reset();
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
for (var i = ibStart; i < cbSize; i++)
{
unchecked
{
this.hash ^= array[i];
this.hash *= FnvPrime;
}
}
}
protected override byte[] HashFinal()
{
return BitConverter.GetBytes(this.hash);
}
private void Reset()
{
this.hash = FnvOffsetBasis;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If you were being completely asinine you could move the <code>Initialize</code> method to a new common ancestor class. The amount of code you would write for that common class would exceed the amount of code you would save from duplication though, in other words, not worth it. Alternatively, you can move the <code>Reset</code> logic in to the <code>Initialize</code> method, and remove <code>Reset</code> entirely, and just call <code>Initialize</code> in the constructor.</p>\n\n<p>I think two factors come in to play here:</p>\n\n<ol>\n<li>The basic Object-model of the Hashing systems is pretty well structured. The common-code is already abstracted to higher inheritance levels, so the amount of required duplication is really small (Kudos to the .net library team).</li>\n<li>By design, the FNV1a algorithm is simple and fast. The only difference between the 64 and 32 bit versions is the value and type of the primes and initializers. Because these values are different the core algorithm (due to the low-level bitwise operations) need to be different.</li>\n</ol>\n\n<p>In other words, your code is as good as it gets. Good job. Now, when you get around to the 128, 256, 512, and 1024-bit versions of the FNV1a algorithm, you may find some other opportunities for logic sharing. I suspect that the loops required using a common int-based infrastructure will make things possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T01:35:05.083",
"Id": "39527",
"ParentId": "39515",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:30:39.530",
"Id": "39515",
"Score": "8",
"Tags": [
"c#",
"performance",
"algorithm",
".net",
"hashcode"
],
"Title": "Implementation of the FNV-1a hash algorithm for 32- and 64-bit"
}
|
39515
|
<p><strong>Please note there are newer revisions of this code, <a href="https://codereview.stackexchange.com/q/47840/27623">one here</a>, and <a href="https://codereview.stackexchange.com/q/84536/27623">one here for continuous audio recording</a>.</strong></p>
<p>This is a program I wrote as a .wav audio recording library for Linux. It was developed on a Raspberry Pi, so that may affect the dependencies required.<sup>(1)</sup></p>
<p><strong>wav.h</strong></p>
<pre><code>#include <stdint.h>
typedef struct
{
char RIFF_marker[4];
uint32_t file_size;
char filetype_header[4];
char format_marker[4];
uint32_t data_header_length;
uint16_t format_type;
uint16_t number_of_channels;
uint32_t sample_rate;
uint32_t bytes_per_second;
uint16_t bytes_per_frame;
uint16_t bits_per_sample;
} WaveHeader;
WaveHeader *genericWAVHeader(uint32_t sample_rate, uint16_t bit_depth, uint16_t channels);
WaveHeader *retrieveWAVHeader(const void *ptr);
int writeWAVHeader(int fd, WaveHeader *hdr);
int recordWAV(const char *fileName, WaveHeader *hdr, uint32_t duration);
</code></pre>
<p>Here is the main program:</p>
<pre><code>#include <alsa/asoundlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "wav.h"
WaveHeader *genericWAVHeader(uint32_t sample_rate, uint16_t bit_depth, uint16_t channels)
{
WaveHeader *hdr;
hdr = malloc(sizeof(*hdr));
if (!hdr) return NULL;
memcpy(&hdr->RIFF_marker, "RIFF", 4);
memcpy(&hdr->filetype_header, "WAVE", 4);
memcpy(&hdr->format_marker, "fmt ", 4);
hdr->data_header_length = 16;
hdr->format_type = 1;
hdr->number_of_channels = channels;
hdr->sample_rate = sample_rate;
hdr->bytes_per_second = sample_rate * channels * bit_depth / 8;
hdr->bytes_per_frame = channels * bit_depth / 8;
hdr->bits_per_sample = bit_depth;
return hdr;
}
int writeWAVHeader(int fd, WaveHeader *hdr)
{
if (!hdr)
return -1;
write(fd, &hdr->RIFF_marker, 4);
write(fd, &hdr->file_size, 4);
write(fd, &hdr->filetype_header, 4);
write(fd, &hdr->format_marker, 4);
write(fd, &hdr->data_header_length, 4);
write(fd, &hdr->format_type, 2);
write(fd, &hdr->number_of_channels, 2);
write(fd, &hdr->sample_rate, 4);
write(fd, &hdr->bytes_per_second, 4);
write(fd, &hdr->bytes_per_frame, 2);
write(fd, &hdr->bits_per_sample, 2);
write(fd, "data", 4);
uint32_t data_size = hdr->file_size - 36;
write(fd, &data_size, 4);
return 0;
}
int recordWAV(const char *fileName, WaveHeader *hdr, uint32_t duration)
{
int err;
int size;
snd_pcm_t *handle;
snd_pcm_hw_params_t *params;
unsigned int sampleRate = hdr->sample_rate;
int dir;
snd_pcm_uframes_t frames = 32;
const char *device = "plughw:1,0"; // USB microphone
// const char *device = "default"; // Integrated system microphone
char *buffer;
int filedesc;
/* Open PCM device for recording (capture). */
err = snd_pcm_open(&handle, device, SND_PCM_STREAM_CAPTURE, 0);
if (err)
{
fprintf(stderr, "Unable to open PCM device: %s\n", snd_strerror(err));
return err;
}
/* Allocate a hardware parameters object. */
snd_pcm_hw_params_alloca(&params);
/* Fill it in with default values. */
snd_pcm_hw_params_any(handle, params);
/* ### Set the desired hardware parameters. ### */
/* Interleaved mode */
err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
if (err)
{
fprintf(stderr, "Error setting interleaved mode: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return err;
}
/* Signed 16-bit little-endian format */
if (hdr->bits_per_sample == 16) err = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);
else err = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_U8);
if (err)
{
fprintf(stderr, "Error setting format: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return err;
}
/* Two channels (stereo) */
err = snd_pcm_hw_params_set_channels(handle, params, hdr->number_of_channels);
if (err)
{
fprintf(stderr, "Error setting channels: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return err;
}
/* 44100 bits/second sampling rate (CD quality) */
sampleRate = hdr->sample_rate;
err = snd_pcm_hw_params_set_rate_near(handle, params, &sampleRate, &dir);
if (err)
{
fprintf(stderr, "Error setting sampling rate (%d): %s\n", sampleRate, snd_strerror(err));
snd_pcm_close(handle);
return err;
}
hdr->sample_rate = sampleRate;
/* Set period size*/
err = snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir);
if (err)
{
fprintf(stderr, "Error setting period size: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return err;
}
/* Write the parameters to the driver */
err = snd_pcm_hw_params(handle, params);
if (err < 0)
{
fprintf(stderr, "Unable to set HW parameters: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return err;
}
/* Use a buffer large enough to hold one period */
err = snd_pcm_hw_params_get_period_size(params, &frames, &dir);
if (err)
{
fprintf(stderr, "Error retrieving period size: %s\n", snd_strerror(err));
snd_pcm_close(handle);
return err;
}
size = frames * hdr->bits_per_sample / 8 * hdr->number_of_channels; /* 2 bytes/sample, 2 channels */
buffer = (char *) malloc(size);
if (!buffer)
{
fprintf(stdout, "Buffer error.\n");
snd_pcm_close(handle);
return -1;
}
err = snd_pcm_hw_params_get_period_time(params, &sampleRate, &dir);
if (err)
{
fprintf(stderr, "Error retrieving period time: %s\n", snd_strerror(err));
snd_pcm_close(handle);
free(buffer);
return err;
}
uint32_t pcm_data_size = hdr->sample_rate * hdr->bytes_per_frame * (duration / 1000);
hdr->file_size = pcm_data_size + 36;
filedesc = open(fileName, O_WRONLY | O_CREAT, 0644);
err = writeWAVHeader(filedesc, hdr);
if (err)
{
fprintf(stderr, "Error writing .wav header.");
snd_pcm_close(handle);
free(buffer);
close(filedesc);
return err;
}
int totalFrames = 0;
for(int i = ((duration * 1000) / (hdr->sample_rate / frames)); i > 0; i--)
{
err = snd_pcm_readi(handle, buffer, frames);
totalFrames += err;
if (err == -EPIPE) fprintf(stderr, "Overrun occurred: %d\n", err);
if (err < 0) err = snd_pcm_recover(handle, err, 0);
// Still an error, need to exit.
if (err < 0)
{
fprintf(stderr, "Error occured while recording: %s\n", snd_strerror(err));
snd_pcm_close(handle);
free(buffer);
close(filedesc);
return err;
}
write(filedesc, buffer, size);
}
close(filedesc);
snd_pcm_drain(handle);
snd_pcm_close(handle);
free(buffer);
return 0;
}
</code></pre>
<p><sup>(1)</sup>: Right now the program needs a USB device for input. I left a comment where the input device is declared so that it can be changed as needed.
Also, I'm not sure the program will work as intended if PulseAudio is installed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T01:03:48.183",
"Id": "66356",
"Score": "0",
"body": "Apparently, Rasberry Pi is little-endian by default; but can be big-endian."
}
] |
[
{
"body": "<p>A few things jump out at me immediately:</p>\n\n<ol>\n<li><p>Use <code>sizeof()</code> whenever you need the size of something with non-dynamic allocation. In other words, all of your <code>write</code> calls on the <code>WaveHeader</code> struct members should be using <code>sizeof</code>, not hard coded sizes.</p></li>\n<li><p>Allocation and initialization should be separate concerns. There's no need to have the same method that initializes a struct allocate it (unless it's an opaque pointer, or you actually care where it's allocated). There's no reason your <code>WaveHeader</code> can't be on the stack. </p>\n\n<ul>\n<li><p>As a general rule, use automatic allocation (\"the stack\") first and only move to dynamic allocation when you have some compelling reason (the reason usually being size varying, too big to fit on the stack, multithreading concerns, etc).</p></li>\n<li><p>Separating out initialization and allocation makes it possible for the user of the API to decide what to do with memory. Unless you <em>need</em> to make this decision for them, don't.</p></li>\n<li><p>If you're feeling lazy, you can always have a <code>genericWavHeaderInit</code> and <code>genericWaveHeaderCreate</code></p></li>\n</ul></li>\n<li><p>Library code should <strong>never</strong> output anything. Use error codes and allow the caller to handle error reporting. What if the error should be ignored for some reason? Well, too late. You already put out an error.</p>\n\n<ul>\n<li>Imagine if standard library functions output errors to <code>stderr</code>. It would be absurd :).</li>\n</ul></li>\n<li><p>Operate on resources, not what you need to create those resources</p>\n\n<ul>\n<li><p><code>RecordWAV</code> should take a <code>snd_pcm_t</code> and allocate/initialize it.</p></li>\n<li><p>Summarize to yourself what <code>RecordWAV</code> does. Truly go through all the steps, explaining to yourself what each chunk of code does. It does a lot more than just record a WAV.</p></li>\n<li><p>As a happy side effect, it relieves your hard coded USB port. That really should come from a command line argument or a config file or something. Wanting to use different USB ports should not require a recompile.</p></li>\n<li><p>Another happy side effect: your resource cleanup code doesn't have to be repeat a trillion times with every exit point (much less repetitive, but much more important: less error prone!)</p></li>\n</ul></li>\n<li><p>This is fairly subjective, but I don't like your naming scheme. </p>\n\n<ul>\n<li><p><code>subjectVerb</code> has the nice effect of provided a \"namespace\" of sorts (<em>every</em> widely used C library has a standard prefix (<code>curl_</code>, <code>qt_</code>, <code>glib_</code>, <code>apr_</code>, etc).</p></li>\n<li><p>A suffix technically accomplishes the same namespacing effect, but it's much, much rarer</p></li>\n</ul></li>\n<li><p>Likewise, when a function's sole purpose is to operate on some object (i.e. struct) that struct should typically be the first parameter (<code>writeWAVHeader</code>).</p></li>\n<li><p>If you're going to go the camelCase route (which I don't know if I would in C, but that's subjective) I would stick with strict camel casing (<code>writeWavHeader</code>). It's less visually jarring, it's easier to type, and anyone familiar with WAV will understand.</p>\n\n<ul>\n<li>Same with <code>RIFF_marker</code></li>\n</ul></li>\n<li><p>Include your own headers first, and then other headers. If your <code>wav.h</code> had a hidden dependency on a file, it could get hidden by the source file including it. It wouldn't be until you tried to include it without including that hidden dependency that you'd get a sudden mysterious undeclared symbol error.</p></li>\n<li><p><code>retrieveWAVHeader</code> isn't defined. It also seems to be an unnecessary version of <code>(WaveHeader*) ptr</code></p></li>\n<li><p>If the return of <code>recordWAV</code> is an ALSA constant (since it's one of the error codes), you should use whatever ALSA's success constant is. I can't imagine that it wouldn't be 0, but consistency with the other possible returns would be nice.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T00:25:35.657",
"Id": "39524",
"ParentId": "39521",
"Score": "21"
}
},
{
"body": "<p>In C, I'd rather accept a pointer to a struct to be initialized than return newly allocated heap memory. It's clear that the caller owns the memory. The caller has the flexibility to pass you a pointer to a <code>struct</code> on its stack.</p>\n\n<pre><code>void initWAVHeader(WaveHeader *hdr, uint32_t sample_rate, uint16_t bit_depth, uint16_t channels);\n</code></pre>\n\n<p>The same goes for the rest of your functions. I'd make <code>WaveHeader *</code> the first parameter to all of the functions to give your library a sense of design consistency.</p>\n\n<p>To fill in the struct, consider keeping a global <code>static</code> prototype. Instead of setting each field piecemeal, <code>memcpy()</code> the entire struct, then fill in the parts you need to change.</p>\n\n<hr>\n\n<p>To write the header, you should be able to write the entire struct at once, as long as the struct is correctly packed in memory. Putting <code>__attribute__((__packed__))</code> at the end of your <code>struct</code> declaration should ensure that GCC will not add padding between the members.</p>\n\n<hr>\n\n<p>I take issue with this style:</p>\n\n<pre><code>/* Signed 16-bit little-endian format */\nif (hdr->bits_per_sample == 16) err = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);\nelse err = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_U8);\nif (err)\n{\n fprintf(stderr, \"Error setting format: %s\\n\", snd_strerror(err));\n snd_pcm_close(handle);\n return err;\n}\n</code></pre>\n\n<p>The problems I see are:</p>\n\n<ol>\n<li>The <code>if</code> line is too long for my taste. The body should have been on a separate line.</li>\n<li>Too much repetition (of the <code>snd_pcm_hw_params_set_format()</code> call), and yet it's not immediately obvious what the code branches have in common.</li>\n<li>In C code where you have to check the error code on every library call, I like to make it a habit to <em>never</em> call a library function outside of an <code>if</code> condition. It's an idiom — <code>if (OK != (err = library_call(…))) { handle_error(); }</code>.</li>\n</ol>\n\n<p>So, I'd write it this way (with an extra layer of parentheses to squelch compiler warnings about assigning inside an <code>if</code>):</p>\n\n<pre><code>/* Signed 16-bit little-endian format or Unsigned 8-bit? */\nenum snd_pcm_format_t fmt = (hdr->bits_per_sample == 16) ?\n SND_PCM_FORMAT_S16_LE : SND_PCM_FORMAT_U8;\nif ((err = snd_pcm_hw_params_set_format(handle, params, fmt))) {\n fprintf(stderr, \"Error setting format: %s\\n\", snd_strerror(err));\n snd_pcm_close(handle);\n return err;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T00:29:01.387",
"Id": "39525",
"ParentId": "39521",
"Score": "13"
}
},
{
"body": "<p>Your <code>recordWAV</code> is supposed to receive a header that has been setup with\n<code>genericWAVHeader</code>. That function takes the desired sample rate and applies\nit to the header. However, within <code>recordWAV</code>, the functions that setup the\nPCM handle parameters determine the real sample rate (your call to\n<code>snd_pcm_hw_params_set_rate_near</code> modifies the suggested sample rate) and so\nthe rate encoded in the header passed to <code>recordWAV</code> can be incorrect.</p>\n\n<p>With your current arrangement there is no way to fix this. Which brings me\nto...</p>\n\n<p>I think the public interface is wrong.</p>\n\n<ul>\n<li><p>The header should not be public. The caller needs to know nothing about the\nheader as it is an implementation detail of the WAV file.</p></li>\n<li><p>There is no reason to ask the function to open a file as well as all of the\nother things it must do. Just pass in a file descriptor (or a <code>FILE*</code>)</p></li>\n</ul>\n\n<p>So I would change the function prototype to:</p>\n\n<pre><code>int record_wav(int fd,\n const char *device,\n uint32_t sample_rate,\n uint16_t bit_depth,\n uint16_t channels,\n uint32_t duration);\n</code></pre>\n\n<p>The record function is much too big and the error handling is repeated much\ntoo often. I would prefer to see a simple function like this:</p>\n\n<pre><code>int record_wav(int fd, ...)\n{\n snd_pcm_t *h;\n int err = open_pcm_channel(&h, ...);\n if (err) {\n fprintf(stderr, \"Error opening channel: %s\\n\", snd_strerror(err));\n return err;\n }\n err = write_header(fd, &h, ...);\n if (!err) {\n err = write_data(fd, &h, ...);\n }\n if (err) {\n fprintf(stderr, \"Error: %s\\n\", snd_strerror(err));\n }\n snd_pcm_drain(h);\n snd_pcm_close(h);\n return err;\n}\n</code></pre>\n\n<p>In this, <code>open_pcm_channel()</code> opens the channel and configures it according to\nthe call parameters to <code>record_wav</code>, <code>write_header</code> is the only thing to know\nabout the header and <code>write_data</code> is the only thing to know about obtaining\nand writing data and it creates and frees the necessary buffer locally.</p>\n\n<p>In <code>open_pcm_channel()</code> above, the <code>snd_pcm_hw_params_t *params;</code> is\nallocated, used and and freed within that function (not that you currently\ndon't seem to free it). The chain of calls to 'snd' functions can be something\nlike:</p>\n\n<pre><code>snd_pcm_hw_params_alloca(&params);\nsnd_pcm_hw_params_any(handle, params);\nerr = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);\nif (!err) {\n err = snd_pcm_hw_params_set_format(handle, params, format);\n}\nif (!err) {\n err = snd_pcm_hw_params_set_channels(handle, params, hdr->number_of_channels);\n}\nif (!err) {\n err = snd_pcm_hw_params_set_rate_near(handle, params, &sampleRate, &dir);\n}\nif (!err) {\n err = snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir);\n}\nif (!err) {\n err = snd_pcm_hw_params(handle, params);\n}\nif (!err) {\n err = snd_pcm_hw_params_get_period_size(params, &frames, &dir);\n}\nif (!err) {\n err = snd_pcm_hw_params_get_period_time(params, &sampleRate, &dir);\n}\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>snd_pcm_hw_params_alloca(&p);\nsnd_pcm_hw_params_any(h, p);\nif ((err = snd_pcm_hw_p_set_access(h, p, SND_PCM_ACCESS_RW_INTERLEAVED))\n || ((err = snd_pcm_hw_params_set_format(h, p, format)))\n || ((err = snd_pcm_hw_params_set_channels(h, p, hdr->number_of_channels)))\n || ((err = snd_pcm_hw_params_set_rate_near(h, p, &sampleRate, &dir)))\n || ((err = snd_pcm_hw_params_set_period_size_near(h, p, &frames, &dir)))\n || ((err = snd_pcm_hw_params(h, p)))\n || ((err = snd_pcm_hw_params_get_period_size(p, &frames, &dir)))\n || ((err = snd_pcm_hw_params_get_period_time(p, &sampleRate, &dir)))) {\n // handle error\n}\n</code></pre>\n\n<p>Note that the call to <code>snd_pcm_hw_params_get_period_time</code> seems redundant and\nits call parameter <code>sampleRate</code> is misnamed (function gets the time not the\nrate). Also the call to <code>snd_pcm_hw_params_get_period_size</code> seems redundant\nbecause <code>snd_pcm_hw_params_set_period_size_near</code> returned the size used in its\ncall parameter.</p>\n\n<p>The WAV file format uses little-endian numbers in the header. If you are\nrunning on a big-endian CPU your functions will not write the header\ncorrectly.</p>\n\n<p>You have no check for errors on opening or writing the file.</p>\n\n<p>Your <code>params</code> is not checked for allocation error and is not freed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T23:30:43.560",
"Id": "66344",
"Score": "0",
"body": "That long chain could be `err = snd_pcm_func1() || snd_pcm_func2() || snd_pcm_func_last()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T00:57:49.080",
"Id": "66354",
"Score": "0",
"body": "@200_success IMO that would lose the int value, and leave a boolean in err."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T00:57:53.760",
"Id": "66355",
"Score": "0",
"body": "@200_success - not if you want the final value of `err` to equal the value returned by a failing function. In your example `err` will hold 0 or 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T02:56:53.223",
"Id": "66361",
"Score": "0",
"body": "Oh, right. I was thinking of the `||` operator in e.g. Perl or JavaScript, which gives the first truthy value."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T19:49:31.243",
"Id": "39556",
"ParentId": "39521",
"Score": "8"
}
},
{
"body": "<h3>Portability</h3>\n\n<ul>\n<li><p>Right now you have a pretty large dependency staring right at you on the first line.</p>\n\n<blockquote>\n<pre><code>#include <alsa/asoundlib.h>\n</code></pre>\n</blockquote>\n\n<p>With that one declaration, I now know that your \"library\" is tailored to a specific sound architecture. Try running your code on Windows or a Mac, and your library won't cut it.</p>\n\n<p>Instead, you may need to write a wrapper for a great library named <a href=\"http://www.portaudio.com/\" rel=\"nofollow noreferrer\">PortAudio</a>. Just read the first paragraph on their website if you don't believe me in thinking that one of the best C libraries out there.</p>\n\n<blockquote>\n <p>PortAudio is a free, cross-platform, <a href=\"http://www.portaudio.com/license.html\" rel=\"nofollow noreferrer\">open-source</a>, audio I/O library. \n It lets you write simple audio programs in 'C' or C++ that will\n compile and run on many platforms including Windows, Macintosh OS X,\n and Unix (OSS/ALSA). It is intended to promote the exchange of audio\n software between developers on different platforms. <a href=\"http://www.portaudio.com/apps.html\" rel=\"nofollow noreferrer\">Many applications</a>\n use PortAudio for Audio I/O.</p>\n</blockquote>\n\n<p>I think your choice is clear. Ditch the DIY method for dealing with a ton of sound architecture API's, and create a wrapper for the PortAudio library. You won't find yourself disappointed.</p></li>\n<li><p>On top of the sound architecture dependency, you then assign another dependency to a <em>specific device</em>.</p>\n\n<blockquote>\n<pre><code>const char *device = \"plughw:1,0\"; // USB microphone\n</code></pre>\n</blockquote>\n\n<p>How is this a library? Luckily, PortAudio also can do all of the hard work for you here as well, with the function <code>Pa_GetDefaultInputDevice()</code>.</p></li>\n</ul>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p>You probably shouldn't use the <code>write()</code> function anymore since they aren't standardized; instead prefer <code>fwrite()</code>.</p>\n\n<blockquote>\n <p><strong>C99 & C11 §7.19</strong></p>\n \n <p>Many implementations of the C runtime environment, most notably the\n UNIX operating system, provide, aside from the standard I/O library’s\n <code>fopen</code>, <code>fclose</code>, <code>fread</code>, <code>fwrite</code>, and <code>fseek</code>, a set of unbuffered I/O\n services, <code>open</code>, <code>close</code>, <code>read</code>, <code>write</code>, and <code>lseek</code>. The C89 Committee\n decided not to standardize the latter set of functions.</p>\n</blockquote>\n\n<p>In addition, buffered I/O is always faster than unbuffered. There are cases where you might want to use unbuffered, such as whenever you want to ensure that the output has been written before continuing. But in this case you will want to use <code>fwrite()</code>.</p></li>\n<li><p><code>fopen()</code>, a widely-used file I/O functions that you are using, got a facelift in C11. It now supports a new exclusive create-and-open mode (<code>“...x“</code>). The new mode behaves like <code>O_CREAT|O_EXCL</code> in POSIX and is commonly used for lock files. The <code>“...x”</code> family of modes includes the following options:</p>\n\n<ul>\n<li><p><code>wx</code> create text file for writing with exclusive access.</p></li>\n<li><p><code>wbx</code> create binary file for writing with exclusive access.</p></li>\n<li><p><code>w+x</code> create text file for update with exclusive access.</p></li>\n<li><p><code>w+bx</code> or <code>wb+x</code> create binary file for update with exclusive access.</p></li>\n</ul>\n\n<p>Opening a file with any of the exclusive modes above fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access. Additionally, a safer version of <code>fopen()</code> called <code>fopen_s()</code> is also available. That is what I would use in your code if I were you, but I'll leave that up for you to decide and change.</p></li>\n</ul>\n\n<h3>Library Design</h3>\n\n<ul>\n<li><p>Your whole library was built to write out audio to a <code>.wav</code> file, and it works. But what if I want to write out a <code>.wav</code> file the way Apple writes them? (yes, they are different from the way Windows writes them for some reason) Or what if I want a <code>.flac</code> file? I see you have written a <a href=\"https://codereview.stackexchange.com/questions/38944/wave-to-flac-encoder-in-c\"><code>.wav</code> to <code>.flac</code> converter</a>, but converting between formats takes an unnecessary amount of time. </p>\n\n<p>As a programmer, you should always be looking for ways to make your program processes more dynamic and efficient (optimally, at the same time). Storing the audio directly into a <code>.flac</code> file would be more efficient, for example, than converting an audio file to the specific codec. So how can we do this?</p>\n\n<p>Enter in <a href=\"http://www.mega-nerd.com/libsndfile/\" rel=\"nofollow noreferrer\">libsndfile</a>. This library can read and write almost every form of audio codec you can think of. It's more dynamic than your current implementation, and it is easier to switch between the output audio file types.</p></li>\n</ul>\n\n<h3>Syntax/Style</h3>\n\n<ul>\n<li><p>You should almost always be initializing variables when you declare them.</p>\n\n<pre><code>WaveHeader *hdr = malloc(sizeof(*hdr));\n</code></pre></li>\n<li><p>You switch between camelCase and snake_case. You need to be consistent.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-16T23:33:27.377",
"Id": "177773",
"Score": "0",
"body": "\"This is a program I wrote as a .wav audio recording library for Linux.\" I don't see how most of these recommendations are useful. If you're creating a library for Linux, what's wrong with using POSIX functions (`write` etc)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-18T18:34:19.550",
"Id": "178062",
"Score": "0",
"body": "@jacwah I don't mean to be rude, but did you even read my review? I explained the problem with using `write()` in my answer quite thoroughly I think. And even if the question stated that is was written for Linux, there is no problem with making recommendations to have the library be more portable (which is how libraries should strive to be)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-18T18:43:01.527",
"Id": "178063",
"Score": "0",
"body": "Sorry, I might have been the rude one. I did read the review but thought it wasn't really tailored to the question. Cross platform libraries are great - but that doesn't always have to be the goal. There's nothing wrong with the answer though, I realise that my comment must sound very harsh."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T03:41:40.297",
"Id": "47694",
"ParentId": "39521",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39524",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:23:52.020",
"Id": "39521",
"Score": "33",
"Tags": [
"performance",
"c",
"linux",
"audio",
"raspberry-pi"
],
"Title": "Recording audio in C"
}
|
39521
|
<p>I'm currently writing a script and I decided to run cane over it to look for some issues, and the following method was highlighted. I've done my best to cut it back, and at this point I'm inclined to leave it as-is, however cane is still giving it a pretty high rating of 23 (15 is the point it starts complaining) so I wanted to get some more input. Other than perhaps splitting fetching and generating does anyone have any ideas?</p>
<pre><code>def self.generate(template, output_file, company)
puts 'Fetching data...'
@data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data
valid_keys = @data.keys.sort {|a,b| -(a <=> b)}[0,10]
@data = @data.select {|k, _| valid_keys.include? k}
valid_keys = @data.keys.sort {|a,b| -(a <=> b)}[0,2]
loop do
break if :done == choose {|menu| timesheet_menu valid_keys, menu}
end
puts 'Generating output...'
# Used as a result of the ERB binding
#noinspection RubyUnusedLocalVariable
data = @data.select {|k, _| valid_keys.include? k}
File.write(output_file, ERB.new(File.read(template), nil, '-').result(binding))
end
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I just split it, and ended up with the below function, which still scores 19 due to the various lambdas used to control sorting and filtering the data despite being pretty easy to follow still:</p>
<pre><code>def self.fetch_data(company)
data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data
valid_keys = data.keys.sort {|a,b| -(a <=> b)}[0,10]
data = data.select {|k, _| valid_keys.include? k}
valid_keys = data.keys.sort {|a,b| -(a <=> b)}[0,2]
loop do
break if :done == choose {|menu| timesheet_menu data, valid_keys, menu}
end
data.select {|k, _| valid_keys.include? k}
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:27:16.630",
"Id": "66323",
"Score": "3",
"body": "I did an edit based on your \"final code\", though I confess I'm not familiar with that term."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T04:50:48.797",
"Id": "66369",
"Score": "0",
"body": "@CarySwoveland: Fixed that too :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-10T17:56:52.070",
"Id": "264169",
"Score": "0",
"body": "I have rolled back revisions that were based on an answer. Please see *[What to do when someone answers](http://codereview.stackexchange.com/help/someone-answers)*."
}
] |
[
{
"body": "<p>Matthew, it appears to me that you are only making use of the two elements of <code>data</code> whose keys are the top two in the sort. Please correct me if I am wrong. If that is the case, I believe your code (after \"edit\") can be simplified to this:</p>\n\n<pre><code> def self.fetch_data(company)\n data = Provider::GenericProvider.create_provider(company['type'].to_sym, company).data\n data = data.sort {|(k1,_),(k2,_)| -(k1<=>k2)}.first(2)\n loop do\n break if :done == choose {|menu| timesheet_menu data, data.map(&:first), menu}\n end\n Hash[data]\n end\n</code></pre>\n\n<p>Note that after the sort, <code>data</code> is an array of two 2-tuples, each corresponding to a key-value pair from the original hash. If I misunderstood what you are doing, and you do need to pull out the 10 elements of the hash corresponding to the 10 highest-ranking keys, just change the parameter for <code>first</code> from 2 to 10, then extract the first two elements when you need them (i.e., <code>data.first(2)</code>). You can then retrieve the key values from these 2-tuples or convert <code>data.first(2)</code> to a hash for the return value, as I have done with <code>data</code>.</p>\n\n<p>Edit: Ah, <code>valid_keys</code> is modified by <code>choose</code>. Consider this as a further possibility:</p>\n\n<pre><code> data = Hash[data.sort{|(a, _), (b, _)| -(a <=> b)}.first(10)]\n\n loop do\n break if (keys_chosen = choose {|menu| timesheet_menu data, data.keys.first(2), menu})\n end\n\n data.select {|k, _| keys_chosen.include? k}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T07:20:38.250",
"Id": "66267",
"Score": "0",
"body": "The first sort/filter applies filters the data to the latest 10 entries (the keys are dates in ISO format; somewhat irrelevant, but context). `valid_keys` is initialised to the first two elements initially, `choose ... timesheet_menu` is a `Highline` menu that then displays a menu to the user and asks them which they'd like to use which modifies `valid_keys` as a side effect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T08:57:54.690",
"Id": "66274",
"Score": "0",
"body": "Thanks! I managed to get it down to a score of 14 which puts it below the normal cutoff for warnings using some of the suggestions here. I've included the final code in a further edit to the question if you're interested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T23:37:39.860",
"Id": "66345",
"Score": "0",
"body": "Unfortunately, `Highline#choose` is beyond my control, so I can't implement it this way. The reason for the loop at all is because `#choose` will only handle a single answer from the user, which toggles one of the options on or off (handled by `#timesheet_menu`), and then returns the option chosen as well. `:done` is the option that signifies the user has finished their modifications which drops out of the loop and continues the main logic. See http://highline.rubyforge.org/doc/classes/HighLine.html#M000011 for more on the `Highline` gem. Anyway, thanks a lot for the input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T04:57:27.973",
"Id": "66370",
"Score": "1",
"body": "Instead of `.sort{|(a, _), (b, _)| -(a <=> b)}.first(10)` I would use `.sort_by(&:first)}.last(10).reverse`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T17:19:26.307",
"Id": "66410",
"Score": "0",
"body": "I hadn't considered that, @Nak, (and have tucked it away) but I have a slight preference for what I have. My scorecard has them tied on readability, but the incumbent has the edge on simplicity and (I'm guessing) efficiency."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T12:57:29.310",
"Id": "66905",
"Score": "0",
"body": "@Cary, @Nakilon: I actually prefer a minor modification of tokland's version below: `.sort_by {|key, _| key}.last(10).reverse`. It has the benefits of nak's version being a straight forward, obvious solution and the benefit of the block giving it a very explicit sort order for clarities sake instead of relying on the knowledge that the hash gets split into tuples."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T04:07:04.457",
"Id": "39535",
"ParentId": "39523",
"Score": "3"
}
},
{
"body": "<p>I've taken the code labeled as \"final revision\" in your question. Some notes:</p>\n\n<ul>\n<li><p><code>data = something</code> and then <code>data = another_thing</code>. So <code>data</code> holds two different values, that's confusing (use another variable name).</p></li>\n<li><p>Spaces between lines: Vertical space is very valuable, don't insert blank lines without a reason (for example, to separate logically different parts of the code).</p></li>\n<li><p><code>sort_by</code> is usually a better option than <code>sort</code> (higher level of abstraction).</p></li>\n<li><p><code>xs[0, 2]</code> -> xs.first(2). More declarative.</p></li>\n<li><p><code>break if :done == choose ...</code>. Is that a Yoda-condition? it does not look idiomatic in Ruby.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def self.fetch_data(company)\n provider = Provider::GenericProvider.create_provider(company['type'].to_sym, company)\n data = Hash[provider.data.sort_by { |key, value| key }.reverse.first(10)]\n valid_keys = data.keys.first(2)\n until (choose { |menu| timesheet_menu(data, valid_keys, menu) }) == :done\n end\n data.keys & valid_keys\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T07:05:18.200",
"Id": "66879",
"Score": "0",
"body": "Regarding your return value, is that the same as the select given? In particular, does it return a hash? It looks like it'd just return the keys when I want both. As to `#choose`... it's taking user input and modifying valid_keys based on it. So, technically no it's not the same arguments. At any rate, as addressed with Cary, choose is provided by Highline so I can't really mess with that too much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T08:34:55.643",
"Id": "66883",
"Score": "0",
"body": "Oh, you are right, you want a hash as output. Activesupport has an abstraction for that task, are by chance using it? (i.e. Rails)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T12:21:27.530",
"Id": "66898",
"Score": "0",
"body": "Nope, this is a console app."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T12:36:23.307",
"Id": "66899",
"Score": "0",
"body": "Also, since people (ie. you) seem to still be interested, I bumped the version of the code in the post with what I'm currently using (updated with suggestions from you)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T14:54:45.017",
"Id": "39656",
"ParentId": "39523",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39535",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T23:50:49.243",
"Id": "39523",
"Score": "3",
"Tags": [
"ruby",
"cyclomatic-complexity"
],
"Title": "Ruby function to fetch, filter, and generate data"
}
|
39523
|
<p>I am trying to emulate a basic CPU (Z80) as close as possible. It currently does not read real assembly code, but that will be implemented. If you have any views on how that could be implemented, I'd really appreciate it. Instead of reading real assembly code, I made up a simpler version with the knowledge I had at the time, so it is somewhat compressed to save space.</p>
<p>I am hoping to fully emulate both the RAM and the stack and as you can see I have started on that.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define INC 0b0001
#define INCREMENT 0b00010001 // INC A
#define DEC 0b0010
#define DECREMENT 0b00010010 // DEC A
#define ADD 0b0011
#define ADD_FIXED_WITH_REGISTER 0b00010011 // ADD A, 255
#define ADD_REGISTER_WITH_REGISTER 0b00110011 // ADD A,B
#define SUB 0b0100
#define SUB_FIXED_WITH_REGISTER 0b00010100 // SUB A, 255
#define SUB_REGISTER_WITH_REGISTER 0b00110100 // SUB A,B
#define LD 0b0101
#define LOAD_FIXED_TO_REGISTER 0b00010101 // LD A, 255
#define LOAD_REGISTER_TO_REGISTER 0b00110101 // LD A, B
#define LOAD_FIXED_MEMORY_TO_REGISTER 0b10010101 // LD A, (255)
#define LOAD_REGISTER_TO_REGISTER_MEMORY 0b01110101 // LD (A), B
#define LOAD_FIXED_TO_REGISTER_MEMORY 0b01010101 // LD (A), 255
#define LOAD_REGISTER_TO_FIXED_MEMORY 0b01100101 // LD (255), A
#define LOAD_FIXED_TO_FIXED_MEMORY 0b01000101 // LD (255), 255
#define LOAD_REGISTER_MEMORY_TO_REGISTER 0b10110101 // LD A, (B)
#define AND 0b0110
#define AND_A_WITH_REGISTER 0b00010110 // AND B
#define OR 0b0111
#define OR_A_WITH_REGISTER 0b00110111 // OR B
#define XOR 0b1000
#define XOR_A_WITH_REGISTER 0b00111000 // XOR B
#define JUMP 0b1001
#define JUMP_TO_ADDRESS 0b00001001
#define JUMP_USING_MEMORY 0b00111001
#define PUSH 0b1011
#define PUSH_INTO_STACK 0b00011011
#define POP 0b1100
#define POP_INTO_REGISTER 0b00011100
typedef char bool;
#define true 1
#define false 0
#define byte char
unsigned byte ROM[] = { // Code to run
LOAD_FIXED_TO_REGISTER, 0, 1,
JUMP_TO_ADDRESS, 9,
XOR_A_WITH_REGISTER, 0,
JUMP_TO_ADDRESS, 17,
INCREMENT, 0,
POP_INTO_REGISTER, 1,
JUMP_TO_ADDRESS, 5
};
unsigned byte RAM[255]; // 16 bytes of RAM
//Registers
unsigned int SP = sizeof(RAM)-1; // Stack pointer
unsigned int PC = 0; // Program counter
unsigned byte F = 0; // Flags
unsigned byte A = 0; // Accumulator
unsigned byte B = 0;
unsigned byte C = 0;
unsigned byte D = 0;
unsigned byte E = 0;
unsigned byte H = 0;
unsigned byte L = 0;
void run();
int main() {
run();
return 0;
}
void run() {
byte *Aaddress = &A; // where is the A register in RAM?
byte *Memstart = RAM[0]; // Where does the virtual RAM start in real RAM?
int end = sizeof(ROM); // How much memory does the code take up? (in bytes)
while (PC<end) {
byte *memto = &A; // Everything goes to A register unless specified
byte *memfrom = &A; // Will always overwrite when using
byte usedbytes = 2; // How many bytes this command used
unsigned byte opcode = ROM[PC] & 0xF; // First nibble is opcode/instruction
// Second nibble is opcode's flags
bool firstregister = readBit(&ROM[PC], 4);
bool secondregister = readBit(&ROM[PC], 5);
bool firstpointer = readBit(&ROM[PC], 6);
bool secondpointer = readBit(&ROM[PC], 7);
unsigned byte firstoprand = ROM[PC+1]; // First instruction parameter/oprand
unsigned byte secondoprand = ROM[PC+2]; // Second instruction parameter/oprand
// Decide what two bytes to use in physical RAM
switch(opcode) {
case INC:
if (firstregister) {
memto += firstoprand;
}
break;
case DEC:
if (firstregister) {
memto += firstoprand;
}
break;
case ADD:
if (firstregister) {
memto += firstoprand;
}
if (secondregister) {
memfrom += secondoprand;
} else if (secondpointer) {
memfrom = Memstart+secondoprand;
} else {
memfrom = &secondoprand;
}
usedbytes = 3;
break;
case SUB:
if (firstregister) {
memto += firstoprand;
}
if (secondregister) {
memfrom += secondoprand;
} else if (secondpointer) {
memfrom = Memstart+secondoprand;
} else {
memfrom = &secondoprand;
}
usedbytes = 3;
break;
case AND:
if (firstregister) {
memfrom = Aaddress+firstoprand;
}
break;
case OR:
if (firstregister) {
memfrom = Aaddress+firstoprand;
}
break;
case XOR:
if (firstregister) {
memfrom = Aaddress+firstoprand;
}
break;
case LD:
if (secondregister) {
if (secondpointer) {
memfrom = &RAM[*(Aaddress+secondoprand)];
} else {
memfrom = Aaddress+secondoprand;
}
} else {
if (secondpointer) {
memfrom = &RAM[secondoprand];
} else {
memfrom = &secondoprand;
}
}
if (firstregister) {
if (firstpointer) {
memto = &RAM[*(Aaddress+firstoprand)];
} else {
memto = Aaddress+firstoprand;
}
} else {
if (firstpointer) {
memto = &RAM[firstoprand];
} else {
memto = &firstoprand;
}
}
usedbytes = 3;
break;
case JUMP:
if (firstpointer) {
memfrom = &RAM[firstoprand];
} else {
memfrom = &firstoprand;
}
break;
case PUSH:
if (firstregister) {
memto = &RAM[SP];
memfrom = &firstoprand;
}
break;
case POP:
if (firstregister) {
memfrom = &RAM[SP+1];
memto = Aaddress+firstoprand;
}
break;
}
// Do stuff with memory
switch(opcode) {
case INC:
*memto = *memto+1;
clearBit(&F, 1);
if (*memto == 0)
setBit(&F, 6);
break;
case DEC:
*memto = *memto-1;
clearBit(&F, 1);
if (*memto == 0)
setBit(&F, 6);
break;
case ADD:
*memto += *memfrom;
clearBit(&F, 1);
break;
case SUB:
*memto -= *memfrom;
clearBit(&F, 1);
if (*memto == 0)
setBit(&F, 6);
break;
case AND:
A = A & *memfrom;
clearBit(&F, 0);
clearBit(&F, 1);
if (A == 0)
setBit(&F, 6);
break;
case OR:
A = A | *memfrom;
clearBit(&F, 0);
clearBit(&F, 1);
if (A == 0)
setBit(&F, 6);
break;
case XOR:
A = A ^ *memfrom;
clearBit(&F, 0);
clearBit(&F, 1);
if (A == 0)
setBit(&F, 6);
break;
case LD:
*memto = *memfrom;
break;
case JUMP:
RAM[SP] = PC + usedbytes;
SP--;
PC = *memfrom - usedbytes;
break;
case PUSH:
*memto = *memfrom;
SP--;
break;
case POP:
*memto = *memfrom;
SP++;
break;
}
PC += usedbytes;
}
}
</code></pre>
<p>I would love to get this more condensed and/or use less variables during the interpretation stage. This is a purely for education and to learn how low I can get the CPU cycles, so any bitwise operators would help a lot. </p>
<p>FYI, I have removed all the debugging code, otherwise the paste would be huge. I am also using CodeBlocks IDE and GCC compiler.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>It currently does not read real assembly code, but that will be implemented.</p>\n</blockquote>\n\n<p>Real assembly code might look like <a href=\"http://sgate.emt.bme.hu/patai/publications/z80guide/part4.html#shift\" rel=\"nofollow\">this</a>:</p>\n\n<pre><code>ld a,%11010011 ; A=%11010011, carry=?\nsla a ; A=%10100110, carry=1\nrla ; A=%01001101, carry=1\nrlca ; A=%10011010, carry=0\nsra a ; A=%11001101, carry=0\nrra ; A=%01100110, carry=1\n</code></pre>\n\n<p>To do this code you'd do it in two parts:</p>\n\n<ol>\n<li>Write an \"assembler\", which parses the assembly and emits machine machine code</li>\n<li>Write a CPU emulator as you have done (or manufacture Z80 hardware), which runs the machine code</li>\n</ol>\n\n<p>You have the second part (the CPU emulator) already, so the new software would be an assembler.</p>\n\n<p>An assembler is like a compiler, but for assembly language. Theoretically you could instead write software to parse-and-run assembly language in one step instead of two, like an \"interpreter\" instead of a \"compiler\"; but that (parsing assembly language at run-time) should be much slower to run: therefore, assembling to machine code is the usual first step.</p>\n\n<p>Pseudocode for an assembler might be something like:</p>\n\n<ul>\n<li>for each line in the assembly source input file\n<ul>\n<li>trim leading and trailing whitespace and comments</li>\n<li>extract the first string (which identifies the opcode)</li>\n<li>switch on the opcode string (for example, <code>case \"ld\":</code>)</li>\n<li>emit (to the machine code output file) the opcode</li>\n<li>parse the remainder of the line (for example, <code>a,%11010011</code>) and emit machine code to represent these operands</li>\n</ul></li>\n</ul>\n\n<p>A helpful feature of assembly instead of machine code is that assembly contains named labels and subroutine names, for example <a href=\"http://sgate.emt.bme.hu/patai/publications/z80guide/part2.html#branches\" rel=\"nofollow\">here</a>:</p>\n\n<pre><code> cp $80 ; comparing the unsigned A to 128\n jr c,A_Is_Positive ; if it is less, then jump to the label given\n neg ; multiplying A by -1\nA_Is_Positive: ; after this label, A is between 0 and 128\n</code></pre>\n\n<p>A label will correspond to a location in memory (in the machine code).</p>\n\n<p>You may need a <a href=\"https://www.google.com/search?q=two-pass+assembler\" rel=\"nofollow\">\"two-pass\" assembler</a>. For example, a statement might jump forward to a label which hasn't been defined yet. You need to assemble future statements (until you find the label and know where it is in memory), and then come back and fix (write the label's memory address to) to the operand of your earlier jump instruction.</p>\n\n<p>You load the assembler's output file (machine code) as the input file to your emulator (i.e. the \"ROM\" variable in your program).</p>\n\n<hr>\n\n<blockquote>\n <p>I am hoping to fully emulate both the RAM and the stack and as you can see I have started on that.</p>\n</blockquote>\n\n<p>Woohoo: 16 bytes of RAM! \"Surely, that will be enough for anyone.\"</p>\n\n<pre><code>unsigned byte RAM[255]; // 16 bytes of RAM\n</code></pre>\n\n<p>If you want more than that, you can allocate it using malloc or calloc.</p>\n\n<pre><code>RAM = malloc(1024*8);\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>I would love to get this more condensed and/or use less variables during the interpretation stage.</p>\n</blockquote>\n\n<p>One idea is to define those variables as inline functions; for example, instead of ...</p>\n\n<pre><code>bool firstregister = readBit(&ROM[PC], 4);\n</code></pre>\n\n<p>... try ...</p>\n\n<pre><code>inline bool firstregister() { return readBit(&ROM[PC], 4); }\n</code></pre>\n\n<p>In that case you code would like like:</p>\n\n<pre><code> case INC:\n if (firstregister()) {\n memto += firstoprand();\n }\n break;\n</code></pre>\n\n<p>The advantage of function instead of variables is that if the opcode doesn't use one (as, for example, the <code>INC</code> opcode doesn't use <code>secondoprand</code>) then the sace statemet for that opcode don't call that <code>secondoprand()</code> function and therefore doesn't spend time calculating its value.</p>\n\n<p>Where are your readBit and clearBit functions defined?</p>\n\n<hr>\n\n<p>Another idea is to replace your <code>switch(opcode)</code> statement with a jump table.</p>\n\n<pre><code>// FN_PTR is a pointer to a function, which:\n// - takes no input parameters (because ROM and PC are global variables)\n// - doesn't return the number of bytes used; instead it alters PC before returning\ntypedef void (*FN_PTR)();\n\n// see http://www.z80.info/z80oplist.txt\nFN_PTR opcode_table[] = {\n Handle_NOP,\n Handle_LD_1,\n Handle_LD_2,\n Handle_INC_BC,\n ... etc ...\n};\n</code></pre>\n\n<p>Define your case statements as separate functions:</p>\n\n<pre><code>void Handle_INC_BC()\n{\n ... code to increment the BC and PC registers ...\n}\n</code></pre>\n\n<p>Instead of switch (opcode) you can then do:</p>\n\n<pre><code>// get the function to process this opcode\nFN function = opcode_table[opcode];\n// invoke the function\n(*function)();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:25:25.430",
"Id": "66280",
"Score": "0",
"body": "During compilation it it won't be as simple as split opcode to create byte (then oprands), a lot of the time the oprands are part of the opcode."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:32:39.917",
"Id": "66281",
"Score": "1",
"body": "Yes, I saw that in the table of opcodes at http://www.z80.info/z80oplist.txt ... that is why I suggested (at least two) separate functions for the `LD` opcode."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:37:58.337",
"Id": "66283",
"Score": "0",
"body": "I posted that comment early, apparently I cant newline. I wanted to say also: that '16 bytes of ram' is an artifact of when it did have 16 bytes, it uses 255 now, though, what is the advantage of using `malloc()`? Wont using `firstregister()` actually slow it down as it will have to run it multiple times? Using a \"jump table\" looks like a grate idea though - I will definitely look into that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:45:09.377",
"Id": "66289",
"Score": "0",
"body": "malloc is good iff you want to allocate a lot. I don't know z80 but it's IMO hard to believe it only supports 256 bytes RAM. I mostly mentioned malloc because I wasn't sure whether you knew about dynamic memory allocation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:49:26.347",
"Id": "66290",
"Score": "1",
"body": "Looking through your case statements, I see that firstregister is called at most once per case statement. And it isn't called at all in case JUMP. If (rarely) there is any place where you call it multiple times, then you can call it once and cache the result in a local variable, `byte firstregistervalue = firstregister(); ... use firstregistervalue instead of firstregister for the rest of this case statement ...`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T10:24:46.493",
"Id": "39542",
"ParentId": "39526",
"Score": "4"
}
},
{
"body": "<p>There are a few things which jumped out at me:</p>\n\n<ol>\n<li><p>The biggest issue I have is that your code assumes that this:</p>\n\n<pre><code>unsigned byte A = 0; // Accumulator\nunsigned byte B = 0;\nunsigned byte C = 0;\nunsigned byte D = 0;\nunsigned byte E = 0;\nunsigned byte H = 0;\nunsigned byte L = 0;\n</code></pre>\n\n<p>will guarantee you that <code>&A + 1</code> will point to <code>B</code> which it doesn't. It might work or it might not. Your registers should be an array instead.</p></li>\n<li><p>Your machine state is a set of global variables. I'd actually consider encapsulating this in a <code>struct</code> like this:</p>\n\n<pre><code>struct Machine\n{\n unsigned byte RAM[255];\n\n unsigned int SP;\n unsigned int PC;\n unsigned byte Flags;\n\n unsigned byte registers[7];\n}\n\n// some readability/convenience definitions for register file \nstatic const int B = 0;\nstatic const int C = 1;\nstatic const int D = 2;\nstatic const int E = 3;\nstatic const int H = 4;\nstatic const int L = 5;\nstatic const int HL = 6;\nstatic const int A = 7; // as per http://www.z80.info/zip/z80.pdf the accumulator is actually the last register.\n</code></pre></li>\n<li><p>This statement:</p>\n\n<pre><code>unsigned byte secondoprand = ROM[PC+2]; // Second instruction parameter/operand\n</code></pre>\n\n<p>has a subtle bug: For the last instruction in the <code>ROM</code> this will read one byte past the array if the last instruction only has one operand. Depending on memory layout and compiler this could lead to an access violation - although in most cases it will just silently work and read garbage. It probably won't matter in your case it's still not very nice.</p></li>\n<li><p>Given that there are only 256 opcodes I'd consider creating a jump table for all the opcodes (like the <a href=\"http://mdfs.net/Docs/Comp/Z80/OpCodeMap\" rel=\"nofollow\">main table here</a>) with a function pointer to execute it. The function pointer could take a pointer to the current machine and a pointer to the current instruction stream and return the pointer to the next instruction to allow the function to read additional bytes required for the operation. Then your <code>run</code> function could look like this:</p>\n\n<pre><code>typedef char *(*OpExecFunc)(stuct machine *, char *);\n\nOpExecFunc opcodes[] = {\n ..\n};\n\n\nvoid run(struct machine *machine, char *instructions)\n{\n char *current_op = instructions;\n while (*current_op) // assume NULL terminated instruction stream\n {\n current_op = opcodes[*current_op](machine, current_op);\n }\n}\n</code></pre>\n\n<p>So basically</p>\n\n<ul>\n<li>Read the current opcode</li>\n<li>Call the handler for that opcode</li>\n<li>The handler needs to read additional bytes from the instruction stream if required and return the pointer to the next opcode following it</li>\n<li>If any of the handlers run into an error they can return NULL which will terminate the run loop. They could set an error state with a message explaining what is wrong.</li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:04:42.877",
"Id": "39545",
"ParentId": "39526",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39545",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T00:31:14.837",
"Id": "39526",
"Score": "8",
"Tags": [
"c",
"beginner",
"assembly",
"simulation"
],
"Title": "Improvements/suggestions for my CPU emulator"
}
|
39526
|
<p>I saw this problem posted as an interview question asked at Bloomberg:</p>
<blockquote>
<p>Given an integer N, print numbers from 1 to N in lexicographic order.
Restriction. One cannot use strings or characters.</p>
</blockquote>
<p>Below is my solution to this problem. Can the algorithm be improved?</p>
<pre><code>#!/usr/bin/env python
import sys
import traceback
def printlexnum(i, tens, number):
lexnum = i*tens
for j in range(lexnum,min(number+1,lexnum+tens)):
print j
if number>=lexnum:
printlexnum(i, tens*10, number)
return
try:
if len(sys.argv) < 2:
number = 0
while number < 0:
number = int(raw_input('please enter number >0: '))
if number == 0:
sys.exit(1)
else:
number = int(sys.argv[1])
if number <= 0:
print "Bad argument." + number + " must be greater than zero."
sys.exit(1)
for i in range(1,min(10,number+1)):
print i
printlexnum(i,10, number)
except ValueError, e:
traceback.print_exc()
print sys.argv[1], " Input not an integer"
except Exception, e:
traceback.print_exc()
print sys.argv[1], " Exception thrown"
finally:
a = 1 # dummy line
</code></pre>
|
[] |
[
{
"body": "<p>Okay, let me point out some stylistic things first:</p>\n\n<ul>\n<li>Doing <code>traceback.print_exc()</code> in an except block feels somewhat odd. Either you hide the stack trace by printing your own error message—which is actually helpful to the end user—or you leave the exception as it is.</li>\n<li>Exceptions should be caught locally near to the code which may raise them. So having a big <code>try</code> block with that many lines is not really a good idea. Especially when you are catching <em>all</em> exceptions in the end—you are just hiding stuff that could be totally your fault.</li>\n<li>The <code>finally</code> is useless? If you want to do nothing in a block, then use <code>pass</code>; but in your case, you can just leave the <code>finally</code> block out.</li>\n<li>For exceptions your program could actually recover from, you really should do exactly that. When the user gets prompted for a number and enters something else, give him an error but let them try again.</li>\n<li>In regards to the previous point, you actually have some hint of letting the user try again, with the <code>while number < 0:</code>. However, if the user enters a non-number <code>int()</code> will throw a <code>ValueError</code> and the program will just exit.</li>\n<li>Using <code>sys.exit(1)</code> is like shutting your computer down by plugging the cable. Provide a better way to shut down your program. Use the existing exception mechanism to shut it down.</li>\n<li><code>if number == 0: sys.exit(1)</code> — if you’re not accepting a zero either, why don’t you change the while loops condition to “lower <em>or equals</em> zero”?</li>\n<li><code>printlexnum(i, 10, number)</code> — if the second parameter is always a 10, why have it as a parameter?</li>\n<li><code>return</code> — No need to explicitely return from a function when that’s the last statement of the function and no value is specified.</li>\n</ul>\n\n<p>Moving on to the algorithm:</p>\n\n<ul>\n<li>The order is not correct. For example <code>100</code> is being sorted <em>after</em> <code>19</code>, when it should be sorted after <code>10</code> (like <code>10</code> is sorted after <code>1</code>).</li>\n<li>The for-loop in the “main” program should really be handled by the algorithm too. There should be some high-level <code>printlexnum(n)</code> which just prints all numbers from 1 to n.</li>\n</ul>\n\n<p>The easiest way to get a lexicographic order of numbers is when you sort their string representations because strings are always sorted lexicographically. You can actually do this in a single line:</p>\n\n<pre><code>print('\\n'.join(sorted(map(str, range(1, number + 1)))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T02:34:15.960",
"Id": "66864",
"Score": "0",
"body": "Thank you for all the feedback. BTW, a restriction of the problem (which I have edited) is not to use strings."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T16:47:16.660",
"Id": "39600",
"ParentId": "39529",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T02:33:15.590",
"Id": "39529",
"Score": "1",
"Tags": [
"python",
"interview-questions"
],
"Title": "Printing numbers in lexicographic order"
}
|
39529
|
<p>I recently got started with Elixir. I'm used to F#'s pipes, and <code>Seq.map</code> and LINQ's <code>.Select</code> statements. Things are different in Elixir, and the code I have seems very ugly. Anon functions in anon functions.</p>
<pre><code>defrecord FileData, name: "", date: nil
def filedetails() do
files = File.ls!
datestr = fn {{year, month, day}, _time} -> "#{day}/#{month}/#{year}" end
filedates = files |> (Stream.map &(File.stat!(&1)))
|> (Stream.map &(&1.ctime))
|> Stream.map &(datestr.(&1))
Enum.zip(files,filedates)
|> Enum.map fn {n,d}->FileData[name: n, date: d] end
end
</code></pre>
<p>How should this be done?</p>
|
[] |
[
{
"body": "<p>I'm not sure why you'd need to pipe three different streams - one for every manipulation. I'd probably use one Stream to do all the manipulations together, something like:</p>\n\n<pre><code>filedates = files |> Stream.map &((&1 |> File.stat!).ctime |> datastr.())\n</code></pre>\n\n<p>or</p>\n\n<pre><code>filedates = files |> Stream.map &(File.stat!(&1).ctime |> datastr.())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T12:17:59.040",
"Id": "60017",
"ParentId": "39532",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "60017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T03:56:26.670",
"Id": "39532",
"Score": "7",
"Tags": [
"functional-programming",
"lambda",
"elixir"
],
"Title": "Elixir pipes and anonymous functions"
}
|
39532
|
Elixer is a functional programming language that runs on the Erlang VM. It is closely related to Erlang and Ruby.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T03:58:40.803",
"Id": "39534",
"Score": "0",
"Tags": null,
"Title": null
}
|
39534
|
<p><a href="http://elixir-lang.org/" rel="nofollow"><strong>Elixir</strong></a> is a functional meta-programming aware language built on top of the Erlang VM. It is a dynamic language with flexible syntax with macros support that leverages Erlang's abilities to build concurrent, distributed, fault-tolerant applications with hot code upgrades.</p>
<p>Elixir also provides first-class support for pattern matching, polymorphism via protocols (similar to Clojure's), aliases and associative data structures (usually known as dicts or hashes in other programming languages).</p>
<p>Finally, Elixir and Erlang share the same bytecode and data types. This means you can invoke Erlang code from Elixir (and vice-versa) without any conversion or performance hit. This allows a developer to mix the expressiveness of Elixir with the robustness and performance of Erlang.</p>
<p><strong>Resources</strong></p>
<ul>
<li><a href="http://elixir-lang.org/getting_started/1.html" rel="nofollow">Getting started guide</a></li>
<li><a href="http://elixir-lang.org/docs/" rel="nofollow">Documentation</a></li>
<li><a href="https://peepcode.com/products/elixir" rel="nofollow">Meet Elixir screencast from PeepCode</a> featuring Elixir's creator, José Valim</li>
<li><a href="http://pragprog.com/book/elixir/programming-elixir" rel="nofollow">Programming Elixir</a> by Dave Thomas</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T04:21:22.083",
"Id": "39536",
"Score": "0",
"Tags": null,
"Title": null
}
|
39536
|
Elixir is a functional meta-programming aware language built on top of the Erlang VM. It is a dynamic language with flexible syntax with macros support that leverages Erlang's abilities to build concurrent, distributed, fault-tolerant applications with hot code upgrades.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T04:21:22.083",
"Id": "39537",
"Score": "0",
"Tags": null,
"Title": null
}
|
39537
|
<p>I need a review of the following code for finding all permutations of a string in C++:</p>
<pre><code>List Permute(const String& string)
{
if (string.length == 0)
return EmptyStrings(1);
List prevList = Permute(SubString(string,1,string.length));
List nextList = EmptyStrings(string.length*prevList.length);
for (int i=0; i<prevList.length; i++)
{
for (int j=0; j<string.length; j++)
{
nextList[i*string.length+j] += SubString(prevList[i],0,j);
nextList[i*string.length+j] += string[0];
nextList[i*string.length+j] += SubString(prevList[i],j,string.length-1);
}
}
return nextList;
}
</code></pre>
<p>You may assume the correctness of the following:</p>
<pre><code>class List
class String
List EmptyStrings(int n); // returns a list of 'n' empty strings
String SubString(const String& string,int i,int j); // returns the string 'string[i...j)'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:17:46.580",
"Id": "66311",
"Score": "1",
"body": "This is cheating, but I thought it would be nice to mention that [<algorithm>](http://www.cplusplus.com/reference/algorithm/) has useful functions for this such as [next_permutation](http://www.cplusplus.com/reference/algorithm/next_permutation/), [prev_permutation](http://www.cplusplus.com/reference/algorithm/prev_permutation/), and [is_permutation](http://www.cplusplus.com/reference/algorithm/is_permutation/)."
}
] |
[
{
"body": "<p>You may need to remove duplicates. Consider what your output will be if, for example, your input string is <code>\"aaa\"</code>.</p>\n\n<hr>\n\n<p>Code like this is unusual:</p>\n\n<pre><code>// nextList contains an array of empty strings\nnextList[i*string.length+j] += SubString(prevList[i],0,j);\n</code></pre>\n\n<p>IMO this would be more usual:</p>\n\n<pre><code>// nextList is empty\n// calculate new string\nstring nextString = SubString(prevList[i],0,j)\n + string[0]\n + SubString(prevList[i],j,string.length-1);\nnextList.Add(nextString);\n</code></pre>\n\n<hr>\n\n<p>Returning by value is sometimes necessary but can be inefficient. Your algorithm creates many temporary List objects. A better API might be ...</p>\n\n<pre><code>void Permute(const String& inputString, List& outputList) { ... }\n</code></pre>\n\n<p>... where one empty List is allocated by the caller, and you add to it.</p>\n\n<hr>\n\n<p>This statement may be incorrect ...</p>\n\n<pre><code>List prevList = Permute(SubString(string,1,string.length));\n</code></pre>\n\n<p>... I don't know how <code>returns the string 'string[i...j)'</code> is defined but perhaps this statement should be ...</p>\n\n<pre><code>List prevList = Permute(SubString(string,1,string.length - 1));\n</code></pre>\n\n<hr>\n\n<p>You may run out of memory very quickly. For a string of length <code>n</code> there are <code>n!</code> ('n factorial') permutations. <code>\"what's up doc?\"</code> has 14 characters => 87178291200 (or 0x144C3B2800) i.e. bigger than 2<sup>32</sup> combinations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T10:51:17.177",
"Id": "66277",
"Score": "2",
"body": "Never thought of the possibility of duplicates, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T12:11:59.613",
"Id": "66292",
"Score": "0",
"body": "As to the 'run out of memory' - that will obviously happen regardless of how efficient my method is in terms of memory consumption, due to the number of permutations itself"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T12:21:24.107",
"Id": "66293",
"Score": "0",
"body": "It's true that [Combinatorial optimization](http://en.wikipedia.org/wiki/Combinatorial_optimization) is a non-trivial problem for computer scientists. Perhaps (I don't know) if you search you'll find (previously researched) algorithms for this \"permutations of a string\" problem. IMO there might be a solution which can work for larger strings, by generating/outputing the list of permutations to a (larger than 4 GB) output file on disk."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T13:23:43.753",
"Id": "66296",
"Score": "2",
"body": "Returning by value is unlikely to `inefficient`. RVO and NRVO basically prevent the copy from happening (ie it is elided). So prefer to use the more natural style of return by value. Also with move semantics in C++11 it becomes important to use return by value so that these kick in as expected automatically."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T10:48:59.983",
"Id": "39544",
"ParentId": "39543",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39544",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T10:35:04.047",
"Id": "39543",
"Score": "3",
"Tags": [
"c++",
"strings",
"combinatorics"
],
"Title": "Find all permutations of a string in C++"
}
|
39543
|
<p>I request you to provide insightful suggestions to improve the following code as well as an alternative algorithm to solve it.</p>
<p><strong>Problem Specification:</strong></p>
<blockquote>
<p>We'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.</p>
<p><code>maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3</code></p>
<p><code>maxMirror({1, 2, 1, 4}) → 3</code></p>
<p><code>maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2</code></p>
</blockquote>
<p><strong>Solution:</strong></p>
<pre><code>public class MaxMirror {
public static void main(String[] args) {
MaxMirror max = new MaxMirror();
int[] nums = { 1, 2, 1, 4 };
System.out.println("The maximum length of the mirror is "
+ max.maxMirror(nums));
}
public int maxMirror(int[] nums) {
if (nums.length == 0) {
return 0;
}
// Reverse order of the array
int[] revNums = new int[nums.length];
for (int numIndex = nums.length - 1, revIndex = 0; numIndex >= 0; numIndex--, revIndex++) {
revNums[revIndex] = nums[numIndex];
}
// Hope the sub array of maximum length is the array itself
int subArraysToBeChecked = 1;
for (int len = nums.length; len > 1; len--) {
if (mirrorOfLengthLenExists(nums, revNums, len,
subArraysToBeChecked)) {
return len;
}
// Increase the number of sub-arrays to be checked
subArraysToBeChecked++;
}
// In the worst case return 1
return 1;
}
// Choose start and end i.e. sub-arrays to be checked
public boolean mirrorOfLengthLenExists(int[] nums, int[] revNums, int len,
int subArraysToBeChecked) {
int start = 0;
int end = len - 1;
for (int i = len; i <= nums.length; i++) {
if (mirrorExistsFromStartToEnd(nums, revNums, start, end,
subArraysToBeChecked)) {
return true;
}
start++;
end++;
}
return false;
}
// Check from start to end whether mirrored in the revNums
public boolean mirrorExistsFromStartToEnd(int[] nums, int[] revNums,
int start, int end, int subArraysToBeChecked) {
int revStart = 0;
for (int subArraysChecked = 1; subArraysChecked <= subArraysToBeChecked; subArraysChecked++) {
int noOfElementsEqual = 0;
for (int numIndex = start, revIndex = revStart; numIndex <= end; numIndex++, revIndex++) {
if (revNums[revIndex] != nums[numIndex]) {
break;
} else {
++noOfElementsEqual;
}
}
if (noOfElementsEqual == (end - start + 1)) {
return true;
}
revStart++;
}
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T17:07:51.743",
"Id": "66305",
"Score": "2",
"body": "By your interpretation, what should `maxMirror({1, 2, 1, 2, 1})` return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T17:13:02.937",
"Id": "66306",
"Score": "0",
"body": "@200_success Obviously 5."
}
] |
[
{
"body": "<p>My approach is to have two indexes. The <code>i</code> index starts at the left and the <code>j</code> index starts at the right of the array. For a length of 4, we would do these comparisons in this order.\n<code>(0, 3), (0, 2), (0, 1)</code>, then <code>(1, 3), (1, 2)</code>, then, <code>(2, 3)</code> This is basically a pairwise comparison. (Note the initialization part of the for loop is empty)</p>\n\n<pre><code>int frontIndex = 0;\nint endIndex = sequence.length - 1;\nfor( ; frontIndex < endIndex; frontIndex++)\n{\n for(int i = endIndex ; i > frontIndex; i--)\n {\n //stuff here\n }\n}\n</code></pre>\n\n<p>Once a match is found, we start counting the max length, with one index moving to the left and one to the right. The while condition makes sure we don't go out of bounds. Once we break out of that loop, we may update the max length.</p>\n\n<pre><code>while(frontIndex + currentLength < sequence.length && i - currentLength >= 0)\n{\n if(sequence[frontIndex + currentLength] == sequence[i - currentLength]) \n {\n currentLength++;\n }\n else break;\n}\nif (currentLength > maxLength) maxLength = currentLength;\ncurrentLength = 0;\n</code></pre>\n\n<p>This is the entire class</p>\n\n<pre><code>public class Mirrors \n{\n public static void main(String[] args)\n {\n int maxLength = 1;\n int currentLength = 0;\n int[] sequence = {1, 2, 1, 2, 1};\n int frontIndex = 0;\n int endIndex = sequence.length - 1;\n for( ; frontIndex < endIndex; frontIndex++)\n {\n for(int i = endIndex; i > frontIndex; i--)\n {\n if(sequence[frontIndex] == sequence[i])\n {\n currentLength++;\n while(frontIndex + currentLength < sequence.length && i - currentLength >= 0)\n {\n if(sequence[frontIndex + currentLength] == sequence[i - currentLength]) \n {\n currentLength++;\n }\n else break;\n }\n if (currentLength > maxLength) maxLength = currentLength;\n currentLength = 0;\n }\n }\n }\n System.out.print(\"Max length is \" + maxLength);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:06:00.073",
"Id": "66309",
"Score": "0",
"body": "Garrett, I am not sure your solution works for situations where the first value in the array is not part of the mirror. For example, the data `{1,2,3,2,3,2,3,2,3,2}` should return 9. What does your code produce?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:37:57.733",
"Id": "66313",
"Score": "0",
"body": "You are right. My code is producing 1 for that input. Let me make a small fix..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:45:23.580",
"Id": "66315",
"Score": "1",
"body": "Thank you @rolfl for noticing the problem. I fixed the problem and I think it should work swell now. It was returning 1 as you saw; now it is returning 9."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T13:59:28.687",
"Id": "102107",
"Score": "0",
"body": "I don't see a need to leave the initialization of the for loop empty, it doesn't make sense. the `frontIndex` is being set to 0 to start out with and doesn't look like it is used outside of the loop anyway, you should add it back into the for loop initialization. `currentLength` should be created inside the first if statement, because that is it's scope. you should post your code as a question for review you would make some rep and get a code review as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T14:01:11.723",
"Id": "102108",
"Score": "0",
"body": "if you do post your code please leave a comment here with the link to the post I would love to review it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T13:23:10.680",
"Id": "102559",
"Score": "0",
"body": "@GarrettOpenshaw, I Reviewed your code and posted it as a Question, would you mind taking a peak at it? http://codereview.stackexchange.com/q/57333/18427"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T17:24:31.183",
"Id": "39552",
"ParentId": "39551",
"Score": "4"
}
},
{
"body": "<p>There are a few things you should consider changing in your code. Most of them are trivial, but there's also an alternative algorithm you should consider too.</p>\n\n<p>The easy stuff first:</p>\n\n<ul>\n<li><p>Your method starts with:</p>\n\n<pre><code>if (nums.length == 0) {\n return 0;\n}\n</code></pre>\n\n<p>this could easily be:</p>\n\n<pre><code>if (nums.length <= 1) {\n return nums.length;\n}\n</code></pre>\n\n<p>which would eliminate a small amount of work for conditions which are 'obvious'.</p></li>\n<li><p>You have a code-pattern which I consider to be an 'anti-pattern' - loops with multiple co-dependent indices that are not incremented together. Let me explain... you have:</p>\n\n<pre><code>// Hope the sub array of maximum length is the array itself\nint subArraysToBeChecked = 1;\nfor (int len = nums.length; len > 1; len--) {\n ....\n // Increase the number of sub-arrays to be checked\n subArraysToBeChecked++;\n}\n</code></pre>\n\n<p>In this case, both <code>len</code> and <code>subArraysToBeChecked</code> are co-dependent. You should either make that co-dependency obvious, or you should make the loop-dependence obvious:</p>\n\n<pre><code>for (int len = nums.length; len > 1; len--) {\n // make co-dependency obvious\n int subArraysToBeChecked = nums.length - len + 1;\n ....\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (int len = nums.length, subArraysToBeChecked = 1; len > 1; len--, subArraysToBeChecked++) {\n ....\n}\n</code></pre>\n\n<p>This anti-pattern is apparent in <strong>all</strong> your methods. In <code>maxMirror</code> it is with <code>subArraysToBeChecked</code>, in <code>mirrorOfLengthLenExists</code> it is with both <code>start</code> and <code>end</code>, and in <code>mirrorExistsFromStartToEnd</code> it is with <code>revStart</code>.</p>\n\n<p>In most of these cases the variables are not needed at all. For example, inside <code>mirrorExistsFromStartToEnd</code> you can easily calculate the value as <code>int subArraysToBeChecked = nums.length - len + 1</code></p></li>\n<li><p>Your variable names are very descriptive, but I am almost hesitant to say some of them are too long?</p></li>\n</ul>\n\n<p>OK, on to the algorithm.</p>\n\n<ul>\n<li><p>It may seem to you that having two arrays, one forward, and the other reversed, will make things easier. This is not always true. In this case, I think the second array is a distraction. You should get your head in the 'backward' space as much as in the 'forward' space. Think of it like being right-handed or left-handed. The best solution is to be ambidextrous. What you are doing is converting everything so you can treat it in a right-handed way, when what you should be doing is training yourself to be just as good in both orientations. You are slowing yourself down by having to convert your problem-space in to a structured form of <em>your</em> thinking, instead of thinking in the structure of your problem. OK, pep-talk done.... ;-)</p></li>\n<li><p>On the other hand, what I like about what you are doing is that you are starting optimistically with your algorithm ... you are searching for large mirror-values, and then working smaller and smaller until you find one. This is a <strong>good</strong> thing. It means that you can exit-early from your search. If you start small, and work up, you have to keep searching until you have exhausted the entire problem-space. Also, the bigger mirror values are faster to check than the smaller ones (there are many more smaller ones than larger ones).</p></li>\n<li><p>But... ;-), what you should consider is doing things optimistically from <strong>both</strong> sides of the problem. In other words, start big, and work down, but, you should <strong>also</strong> remember the longest matches you have found so far on the things you have already tested. This will mean that you can exit even earlier if it is convenient, and you never need to test things twice.</p></li>\n</ul>\n\n<p>So, keeping all of that in mind, here is a routine that remembers the longest match it has found, while still looking optimistically. When it gets to smaller searches, it checks to see whether it has already found a match with that overlap, and it exits early.</p>\n\n<p>There is one tricky part here, and that is the logic that makes it only check each position once. The logic goes like this.... Consider the array {1,2,3,8,2,1}. We think optimistically, and check if the entire array is one mirror. We start at 0, and check to see whether it has a 6-sized match if we check backwards from 5. We find that the longest match is {1,2} which is length 2, and there is no six-sized match. We remember this longest match. Now we look for matches of size 5, and, since we have already checked for six-sized from position 0 and 5, we check for positions 0 and 1 against position 4, and position 1 against positions 4 and 5. These checks only hit a size of 1, so it's not better than 2. Note how we only needed to check the stuff that has not yet been checked?</p>\n\n<p>OK, here's the code that can do this:</p>\n\n<pre><code>/**\n * This method will return the length of the largest mirrored data value sequence.\n * Data values are mirrored when a sequence of values also appears in reverse-order in the data. \n * @param data the data to search for sequences.\n * @return the length of the longest mirrored sequence\n */\npublic static final int maxMirror(final int[] data) {\n int maxlen = 0;\n for (int trylen = data.length; trylen > 1; trylen--) {\n if (maxlen >= trylen) {\n // a previous longer attempt found this match already.\n return maxlen;\n }\n int foundlen = findMirror(data, trylen);\n if (foundlen > maxlen) {\n maxlen = foundlen;\n }\n }\n return data.length;\n}\n\nprivate static final int findMirror(final int[] data, final int trylen) {\n int longest = 0;\n\n // margin is how far from the left-right edges we need to be limited to.\n // the values at each margin have never been checked against anything else.\n final int leftmargin = data.length - trylen;\n // what is the index on the margin on the right?\n final int rightmargin = data.length - leftmargin - 1;\n\n // check the value at the left-margin against all unchecked possibilities on the right-side.\n // start with the longest possible match (trylen) and then try smaller attempts.\n for (int right = data.length - 1; right >= rightmargin; right--) {\n int match = compare(data, leftmargin, right, trylen);\n if (match == trylen) {\n return match;\n }\n if (match > longest) {\n longest = match;\n }\n }\n // check the value at the right-margin with never-before-checked left-side values.\n // note we start left at 0 because that will produce the longest possible match.\n // also, we do not check left == leftmargin because that has already been tested in previous loop.\n for (int left = 0; left < leftmargin; left++) {\n int match = compare(data, left, rightmargin, trylen);\n if (match == trylen) {\n return match;\n }\n if (match > longest) {\n longest = match;\n }\n }\n return longest;\n}\n\nprivate static int compare(int[] data, int left, int right, int trylen) {\n // simple function that returns the longest 'overlap' of mirror values of a given length and position. \n for (int i = 0; i < trylen; i++) {\n if (data[left + i] != data[right - i]) {\n // difference when checking the i'th position\n return i;\n }\n }\n // exact match for this length.\n return trylen;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T21:53:29.183",
"Id": "66333",
"Score": "2",
"body": "Really what I expected :)-. I didn't really like my approach. But, I want to learn. To code better like a 'Real Programmer(TM)', like you, one needs to start reading and understanding others programs and algorithms. Thank you once again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:53:27.373",
"Id": "39559",
"ParentId": "39551",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39559",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T16:48:55.150",
"Id": "39551",
"Score": "9",
"Tags": [
"java",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "Codingbat maxMirror challenge"
}
|
39551
|
<p>To add line numbers to a file (via <code>stdin</code> to <code>stdout</code>) we can use <code>cat -n</code> or <code>nl</code>.</p>
<p>Given the file test.txt with:</p>
<blockquote>
<pre><code>hello
hello
bye
</code></pre>
</blockquote>
<p>We can do:</p>
<pre><code>$ cat -n < test.txt
1 hello
2 hello
3 bye
</code></pre>
<p>In languages like AWK, Perl, and Ruby, we often get built-in constructs to process files line-by-line, making this program trivial to write. Here is what I have in Ruby:</p>
<pre><code>line_number = 0;
ARGF.each {|line| printf("%6d\t%s", line_number += 1, line)}
</code></pre>
<p>and granted, in AWK, it is much simpler since the line number is already present.</p>
<p>I've just tried to write this same script in node.js but found myself having to import the built-in <code>fs</code> module and then <em>import three separate third-party modules</em>. My solution is:</p>
<pre><code>var fs = require('fs');
var through = require('through');
var split = require('split');
var sprintf = require('sprintf').sprintf;
var linenum = 0;
var number = through(function (line) {
this.queue(sprintf('%6d\t%s\n', ++linenum, line));
});
process.stdin.pipe(split()).pipe(number).pipe(process.stdout);
</code></pre>
<p>This is not intended to be a code-golfing problem, but rather a question of whether I have missed some built-in support for doing this kind of thing in node. I like the separation of concerns, but what I thought would be a simple script in node turned out rather long. Can it be improved?</p>
|
[] |
[
{
"body": "<p>It seems you need <code>through</code> and <code>split</code> to do the piping right. You do not need <code>sprintf</code> as you could build the number formatting yourself. You also do not need <code>fs</code>, you do not use it anywhere.</p>\n\n<p>Something like</p>\n\n<pre><code>var through = require('through');\nvar split = require('split');\n\nvar linenum = 0;\n\nfunction alignRight( s, n )\n{\n s = s + \"\";\n return s.length > n ? s : new Array( n - s.length + 1 ).join(\" \") + s;\n}\n\nvar number = through(function (line) {\n this.queue( alignRight( ++linenum, 6 ) + \"\\t\" + line + \"\\n\" );\n});\n\nprocess.stdin.pipe(split()).pipe(number).pipe(process.stdout);\n</code></pre>\n\n<p>Does the trick for me. While it seems overkill, the nice thing is that you can pipe data between functions yourself, not needing to rely on the OS shell.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-02T11:19:05.803",
"Id": "105758",
"Score": "0",
"body": "Really really Nice!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T13:47:25.083",
"Id": "40155",
"ParentId": "39554",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40155",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:44:47.573",
"Id": "39554",
"Score": "7",
"Tags": [
"javascript",
"strings",
"node.js",
"io"
],
"Title": "Node.js equivalent of cat -n or nl"
}
|
39554
|
<p>I came up with the following solution to find the number of prime numbers from 1 to <em>n</em>.</p>
<p>I'm wondering if there is a more optimal way.</p>
<pre><code>var max = 10;
var compositeNumbers = {};
mainLoop:
for (var i=2; i<= max;i++)
{
smallLoop:
for (var j=2; j<=Math.ceil(Math.sqrt(i));j++)
{
if (i % j == 0)
{
compositeNumbers[i]=1;
continue mainLoop;
}
}
}
console.log(max - Object.keys(compositeNumbers).length);
</code></pre>
|
[] |
[
{
"body": "<p>I've created the following performance tests to test the changes: <a href=\"http://jsbin.com/EqiKini/3\" rel=\"nofollow noreferrer\">http://jsbin.com/EqiKini/3</a></p>\n\n<p><img src=\"https://i.imgur.com/Cr6XmxK.png\" alt=\"enter image description here\"></p>\n\n<p>I'm going to start out this review by pointing out your algorithm is slightly off! Take a look at compositeNumbers after your code above and you'll see it is: <code>{2: 1, 4: 1, 6: 1, 8: 1, 9: 1, 10: 1}</code>. Clearly 2 is not composite but it will normally work because you exclude 1. The way I would address this is by doing a check if max is less than 3.</p>\n\n<pre><code>function findNumPrimes(max) {\n if(max <= 1) return 0;\n var compositeNumbers = {1: 1}; //1 is composite\n //if (max > 3) {//in retrospect no need for this pre condition as it will be handled by the loop\n mainLoop: for (var i = 4; i <= max; i++) {\n smallLoop: for (var j = 2; j <= Math.ceil(Math.sqrt(i)); j++) {\n if (i % j === 0) {\n compositeNumbers[i] = 1;\n continue mainLoop;\n }\n }\n }\n return max - Object.keys(compositeNumbers).length;\n}\n</code></pre>\n\n<p>As you'll notice I slightly adapted your code so you would use it like <code>console.log(findNumPrimes(10000)); //1229</code></p>\n\n<p>The first notable (and obvious) speed improvement I'll point out is you should probably cache <code>Math.ceil(Math.sqrt(i))</code> in a variable (2 times + speed improvement for max > 100).</p>\n\n<p>An even better implementation would probably make use of the ideas from the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>. I added a case to the performance tests using the sieve find prime number algoritm <a href=\"https://stackoverflow.com/questions/11966520/how-to-find-prime-numbers\">posted here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T21:57:20.877",
"Id": "39566",
"ParentId": "39557",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:19:40.283",
"Id": "39557",
"Score": "7",
"Tags": [
"javascript",
"algorithm",
"primes"
],
"Title": "Number of prime numbers between 1 and n"
}
|
39557
|
<p>In the process of learning F#, I wrote this code that reads lines of input from the console and stores them in a list.</p>
<p>As far as I can tell the code works correctly, but since I'm new to functional programming, I'm not sure if it is written as well as it could have been.</p>
<ol>
<li>Should I have read characters iteratively instead of recursively?</li>
<li>Is there a better alternative to using a <code>StringBuilder</code> object?</li>
<li>Does my code follow proper functional style?</li>
</ol>
<p></p>
<pre><code>open System
/// Appends a character to the string builder and returns the new builder.
/// Characters 10 and 13 (newline and carriage return) are ignored.
/// Returns the updated StringBuilder.
let appendChar char (builder : Text.StringBuilder) =
match char with
| 10 | 13 -> builder
| n ->
let c = Convert.ToChar(n)
builder.Append(c)
/// Finishes building a string by clearing the StringBuilder
/// and appending the string to the end of the list of strings.
/// Empty strings are ignored.
/// Returns a tuple containing the lines and the new StringBuilder.
let finishString lines (builder : Text.StringBuilder) =
let s = builder.ToString()
let l = builder.Length
let newBuilder = builder.Clear()
match l with
| 0 -> (lines, newBuilder)
| _ -> (lines @ [s], newBuilder)
/// Handles a character by appending it to the builder and taking an appropriate action.
/// If char is a newline, finish the string.
/// Returns a tuple containing lines and the new builder.
let handleChar char lines builder =
let newBuilder = appendChar char builder
match char with
| 10 -> finishString lines newBuilder
| c -> (lines, newBuilder)
/// Gets all the lines from standard input until end of input (Ctrl-Z).
/// Empty lines are ignored.
/// Returns a list of strings read.
let rec getLines lines builder =
match Console.Read() with
| -1 -> lines
| c ->
let tuple = handleChar c lines builder
let newLines = fst tuple
let newbuilder = snd tuple
getLines newLines newbuilder
[<EntryPoint>]
let main argv =
Text.StringBuilder()
|> getLines []
|> ... and so on
</code></pre>
|
[] |
[
{
"body": "<p>Some small comments</p>\n\n<pre><code> let tuple = handleChar c lines builder\n let newLines = fst tuple\n let newbuilder = snd tuple\n getLines newLines newbuilder\n</code></pre>\n\n<p>can become</p>\n\n<pre><code> let newlines,newbuilder = handleChar c lines builder\n getLines newLines newbuilder\n</code></pre>\n\n<p>although, if you aren't using <code>getLines</code> anywhere else, there is a good argument for making it</p>\n\n<pre><code>handleChar c lines builder |> getLines\n</code></pre>\n\n<p>by makeing <code>getLines</code> take its argument in tupled form.</p>\n\n<p>The magic number 10 appears a few times, so I would add a literal like</p>\n\n<pre><code>[<Literal>]\nlet newline = 10\n</code></pre>\n\n<p>and then you can pattern match against it.</p>\n\n<p>Also,</p>\n\n<pre><code>Lines @ [s]\n</code></pre>\n\n<p>is bad as <code>@</code> is very slow. You are better to use</p>\n\n<pre><code>s::Lines\n</code></pre>\n\n<p>and then reverse the list at the end.</p>\n\n<p>Your format for reading the characters recursively should be fine as it will get optimised as a tail-call.</p>\n\n<p>Of course, your entire program could be replaced by:</p>\n\n<pre><code>let rec procinput lines= \n match Console.ReadLine() with\n | null -> List.rev lines\n | \"\" -> procinput lines\n | s -> procinput (s::lines)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T18:18:48.063",
"Id": "427706",
"Score": "0",
"body": "Is the order of the cases in `match Console.ReadLine() with …` important? I would guess no, but having them as `s`, `\"\"` and `null` seems to time out a lot more often than `null`, `\"\"`, `s`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T21:31:38.657",
"Id": "39562",
"ParentId": "39558",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "39562",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:51:23.560",
"Id": "39558",
"Score": "9",
"Tags": [
"functional-programming",
"f#"
],
"Title": "Reading input from the console in F#"
}
|
39558
|
<p>I've been solving problems on checkio (and trying to digest other's code) in order to improve my Python.</p>
<p>My main goals are to learn to write more idiomatic Python and to explore the language more fully ("batteries included" is no joke!). I'd like critiques on the following (working) code in terms of pythonic-ness and in terms of my choice of tools/solution method:</p>
<pre><code>def checkio(matrix):
def four_consecutive(group):
for number in set(group):
if str(number)*4 in ''.join(map(str,group)): return True
return False
def search(generators):
for generator in generators:
while True:
try:
if four_consecutive(next(generator)): return True
except StopIteration: break
return False
horizontal = (row for row in matrix)
vertical = ([matrix[i][j] for i in range(len(matrix[j]))] for j in range(len(matrix)))
diagonal1 = ([matrix[j+i][j] for j in range(len(matrix)-i)] for i in range(len(matrix)-3))
diagonal2 = ([matrix[j][j+i] for j in range(len(matrix)-i)] for i in range(1,len(matrix)-3))
diagonal3 = ([matrix[-1*(j+1)][j+i] for j in range(len(matrix)-i)] for i in range(len(matrix)-3))
diagonal4 = ([matrix[-1*(j+i+1)][j] for j in range(len(matrix)-i)] for i in range(1,len(matrix)-3))
if search((horizontal,vertical,diagonal1,diagonal2,diagonal3,diagonal4)): return True
return False
</code></pre>
<p>Matrices in this problem are always square, contain integers 1-9, and the specification asks for a return value of true if 4 consecutive equal integers are in a line horizontally, vertically, or diagonally, and false otherwise. Core Python modules were available for import.</p>
<p>My main goal lately has been to get more comfortable with generators and list comprehensions, and to write shorter code.</p>
|
[] |
[
{
"body": "<p>The efficiency of this check must surely be suffering because of the final check.... <em>create a String for each four-some, and compare it against a reference String</em>. In general this will be slow, but, in particular, there can only be 9 reference strings, so why do you have to calculate it each time? An array with these 9 values would be simple to create, and then you can just say:</p>\n\n<pre><code>if reference[number] in ''.join(map(str,group)): return True\n</code></pre>\n\n<p>I am not suggesting that this is a good solution, just a better/faster solution. The best/fastest solution would not create two string values for comparison, but would leave the values in their native integer format.</p>\n\n<p>Secondly, why do you have 4 diagonals? You should be able to get by with just 2 (since there are only two of them). I have not been able to get my head around this problem quickly enough to understand whether there is a particular use-case requiring the 4, but at face value, this means that you are double-checking your diagonals.</p>\n\n<p>While I understand that you are trying to get a handle on generators and comprehensions, a more simplistic approach to this problem would be more efficient, and probably more readable.</p>\n\n<p>The standard HPC (high-performance-computing) method for this type of problem is to create a logical box that spans the problems space. In this case, the box would be 4 by 4. You then create a cursor that traverses the problem space, where the bottom-right member of the box is on the cursor.</p>\n\n<p>You then test that box for a vertical line above, the cursor (if there is space), a horizontal-line to the left, and the two diagonals in the box.</p>\n\n<p>This type of approach is easy to multi-thread or distribute. There are ways to make the memory access more efficient as well by splitting the problem on clever boundaries when parallelizing.</p>\n\n<p>But, what you want to avoid is generating values for each movement of the box....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:35:33.403",
"Id": "66424",
"Score": "0",
"body": "Good point about the reference array. I think that my method of getting sublists with the six generators is similar to the HPC method you detailed. The 'cursor' is the outer (mostly 'i') variable, and it walks along an 'edge' of the matrix generating 'lines' as lists. There are two generators per diagonal 'direction' walking the cursor down the 'side' and across the 'top' of the matrix to get all the diagonals. So diagonals 1 and 2 handle 'down-right' while 3 and 4 handle 'down-left'. Each one contains unique data."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T15:26:53.697",
"Id": "39596",
"ParentId": "39561",
"Score": "1"
}
},
{
"body": "<p>Combining @rolfls windowing with generators is fairly simple:</p>\n\n<pre><code>import itertools\n\ndef consecutive(group):\n first, second = itertools.tee(group)\n second.next()\n for first, second in itertools.izip(first, second):\n if second != first + 1: return False\n return True\n\ndef iterate_submatrix(matrix, t, l):\n '''yield the horizontals and diagonals of 4x4 subsection of matrix starting at t(op), l(eft) as 4-tuples'''\n submat = [row[l:l+4] for row in matrix[t:t+4]]\n for r in submat: yield tuple(r) \n for c in range (0,4): \n yield tuple(r[c] for r in submat)\n yield tuple(submat[rc][rc] for rc in range (0,4))\n yield tuple(submat[rc][3-rc] for rc in range(0,4))\n\n# sample usage:\nfor item in iterate_submatrix(test_matrix, 0,0):\n print item, consecutive(item)\n</code></pre>\n\n<p>There is probably some perf overhead in the generators here, but they do have the pleasant property of hiding several different selection styles behind a neat facade and also minimizing the index mongering. You could easily parameterize the windowing code to support larger or shorter sequences too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T13:14:05.130",
"Id": "66906",
"Score": "0",
"body": "Yes to minimizing index mongering, itertools, and avoiding string conversion. Learning itertools and functools are what I'm working on right now. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T09:12:05.903",
"Id": "39791",
"ParentId": "39561",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39791",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T20:58:42.157",
"Id": "39561",
"Score": "3",
"Tags": [
"python",
"matrix",
"generator"
],
"Title": "Searching a 2D matrix for a consecutive sequence"
}
|
39561
|
<p>This question is really to help me decide on something. I have started development of my own <em>programming language</em> that I am calling DeliciousWaffle (or maybe samscript).</p>
<p>So far it looks pretty cool. I built a compiler in Python, and associated <code>.dw</code> files with it. These files are like <code>.py</code> or <code>.vbs</code> or <code>.java</code>. They provide the code for the compiler to interpret. I also programmed an IDE for it using wxPython.</p>
<p>Here are a few examples of what it looks like:</p>
<p>The fully functional IDE:</p>
<p><img src="https://i.stack.imgur.com/4Myjl.png" alt="DWIDE"></p>
<p>A calculator program that I wrote in DeliciousWaffle:</p>
<p><img src="https://i.stack.imgur.com/tkDS9.png" alt="Calculator"></p>
<p>And here is the code for the compiler. You can download this if you'd like and try out the syntax.</p>
<pre><code>#deliciouswaffle
import sys
import linecache
varss={}
def Say(vartype,text):
if vartype=='normal':
print text
if vartype=='var':
print varss.get(str(text))
def Set(var,val):
global varss
varss.update({str(var):val})
def Get(var,prmpt):
val=raw_input(prmpt)
try:
val=int(val)
x=val+1
except:
val=str(val)
Set(var,val)
def Loop():
global line
line=0
def IfStr(var1,functlines):
global line
var=varss.get(var1)
try:
x=var+1
line+=functlines
except TypeError:
pass
def IfInt(var1,functlines):
global line
var=varss.get(var1)
try:
x=var+1
pass
except TypeError:
line+=functlines
def Convert(var):
val=varss.get(var)
if type(val) == type('str'):
val=int(val)
if type(val) == type(1):
val=str(val)
varss.update({var:val})
def If(var1,compare,var2,functlines):
global varss
global line
var1=varss.get(str(var1))
var2=varss.get(str(var2))
if compare=='equ':
if var1==var2:
pass
else:
line+=functlines
if compare=='lss':
if var1<var2:
pass
else:
line+=functlines
if compare=='gtr':
if var1>var2:
pass
else:
line+=functlines
def ChangeVar(var,operation,do):
global varss
val=varss.get(var)
if operation=='+':
val+=do
if operation=='-':
val-=do
if operation=='/':
val/=do
if operation=='*':
val*=do
varss.update({var:val})
def CombineVars(newvar,var1,var2,operation):
global varss
var1=int(varss.get(var1))
var2=int(varss.get(var2))
if operation=='+':
val=var1+var2
if operation=='-':
val=var1-var2
if operation=='/':
val=var1/var2
if operation=='*':
val=var1*var2
varss.update({newvar:val})
def End():
global eof
eof=1
line=0
eof=0
try:
program = (sys.argv[1])
except:
program = 'main.dw'
if program == 'main.dw':
try:
f=open('main.dw','r')
f.close()
except:
print 'No Delicious Waffle script loaded.'
print 'Create a script called main.dw, or load one into Delicious Waffle.'
raw_input()
sys.exit()
while eof==0:
try:
line+=1
try:
eval(linecache.getline(program, line))
except:
pass
except:
eof=1
f=open('tempvars.file','w')
f.close()
sys.exit()
</code></pre>
<p>What do you think? Is this worth completing? Or should I leave it be? This question is probably inappropriate for code review, sorry.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-05T05:16:19.370",
"Id": "232744",
"Score": "0",
"body": "`compiler to interpret` - Umm... compilers don't interpret stuff. Please correct such core terminology issues. [This](http://www.c4learn.com/c-programming/compiler-vs-interpreter/) should help clear it up."
}
] |
[
{
"body": "<p>It is a beginning. But currently your code is just a thin wrapper around Python function calls. And of course, there is a security problem with \"eval\", because someone could format your harddisk with the right line, if you execute scripts from untrusted sources.</p>\n\n<p>Maybe you should invent a nice syntax for your language. An easy method to write a parser for it, would be a top-down parser (or recursive descent parser), for simple expressions as demonstrated <a href=\"http://effbot.org/zone/simple-top-down-parsing.htm\">here</a>.</p>\n\n<p>Later, you could even build a parser tree and convert it to assembly. The so-called <a href=\"http://en.wikipedia.org/wiki/Principles_of_Compiler_Design\">\"dragon book\"</a> is the best reference, if you want to know more about building parsers and compilers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:16:21.073",
"Id": "66338",
"Score": "0",
"body": "I've heard people recommend \"the dragon book\" but didn't find it practical. Perhaps more practical if you want to write a parser is to learn to use a well-known tool like \"YACC\"; or I chose a less-well-known but perhaps-easier tool, the \"GOLD Parsing System\". They're for parsing relatively complicated programming languages, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T05:12:32.743",
"Id": "66371",
"Score": "0",
"body": "I might suggest one of the Modern Compiler Design in [ML|C|Java] by A. Appel slightly more direct books and just as rewarding for most"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T12:57:29.560",
"Id": "66388",
"Score": "1",
"body": "I think I'm just going to stick to the thin wrapper for now, thank you for your help though. At least I learned something from this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:10:42.190",
"Id": "39569",
"ParentId": "39565",
"Score": "10"
}
},
{
"body": "<p>I second the recommendation to invent a grammar and use a real parser. A recursive descent parser is very easy to write, and a great place to start. You might also have a look at a <a href=\"http://en.wikipedia.org/wiki/Parsing_expression_grammar\">PEG</a> (Parsing Expression Grammar). It's almost as easy to use a PEG as it is to write a recursive descent compiler, and a PEG can parse more grammars than can a recursive descent compiler.\nHere are two PEGs for Python (I haven't used either of them, so can't vouch for them):</p>\n\n<ul>\n<li><a href=\"http://fdik.org/pyPEG/\">pyPeg</a></li>\n<li><a href=\"https://github.com/erikrose/parsimonious\">parsimonious</a></li>\n</ul>\n\n<p>I don't see a good reason to get the Dragon book <em>yet</em>. Much of what it teaches is how to <em>write</em> the LEXX/YACC type tools, along with language theory. I think it's too deep and too low level for someone who just wants to try creating a language in order to see how it's done. If, however, you do want to dive that deep, it is a very good book.</p>\n\n<p>I would, for now, steer clear of a traditional lex/yacc setup. That's a harder road that can wait until you've had some experience with simpler schemes. However, if you do want to go there, <a href=\"http://www.dabeaz.com/ply/\">PLY</a> is a lex/yacc type parser for Python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T01:58:03.350",
"Id": "66357",
"Score": "0",
"body": "I don't mean to be a nuisance, but I am not understanding how to use the pasrsers.. would you mind explaining how I transcode that to interpret my own syntax? I read up on all the pages you've suggested.. and it isn't making sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T02:43:33.370",
"Id": "66359",
"Score": "1",
"body": "@Sam, I started to, but it's too big a subject. I think I would recommend starting with a recursive descent compiler, though. That's the simplest thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T15:52:41.950",
"Id": "66400",
"Score": "2",
"body": "@SamTubb `How to use parsers?` \"The GOLD Parsing System\" is a parser which doesn't have a python engine but which IMO has good documentation: [the overview](http://www.goldparser.org/about/how-it-works.htm) is that you a) define a \"grammar\" for your language; b) feed the grammar, plus some text (e.g. \"source code\" or \"script\") written into the language, into the parser c) the parser outputs an \"abstract syntax tree\" version, which is (theoretically) easier for you to process than the original script text. The [grammar](http://www.goldparser.org/grammars/index.htm) syntax is parser-specific."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:06:15.260",
"Id": "66420",
"Score": "0",
"body": "I understand now! But I think I'm just going to stick to my method for now. Maybe if this ever becomes serious I'll use pyPeg, I like that one."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T01:35:33.927",
"Id": "39575",
"ParentId": "39565",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": "39575",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T21:43:17.437",
"Id": "39565",
"Score": "18",
"Tags": [
"python",
"interpreter",
"language-design"
],
"Title": "Making my own programming language"
}
|
39565
|
<p>I'm simple looking for what the general preference is between the below options:</p>
<ol>
<li><p>anon function directly to variable</p>
<pre><code>middleware.customer = function(req, res, next){
req.customer = function(){
var customer = false;
if(req.method == "POST") customer = req.body;
if(req.method == "GET") customer = req.query;
return customer;
}();
return next();
}
</code></pre></li>
<li><p>raw build variable up</p>
<pre><code>middleware.customer = function(req, res, next){
req.customer = false;
if(req.method == "POST") req.customer = req.body;
if(req.method == "GET") req.customer = req.query;
return next();
}
</code></pre></li>
<li><p>complete separation</p>
<pre><code>var customer = function(req){
var customer = false;
if(req.method == "POST") customer = req.body;
if(req.method == "GET") customer = req.query;
return customer;
}
middleware.customer = function(req, res, next){
req.customer = customer(req);
return next();
}
</code></pre></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:06:44.860",
"Id": "66334",
"Score": "2",
"body": "Second version looks best IMO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:17:17.087",
"Id": "66340",
"Score": "0",
"body": "That's where I'm at @elclanrs"
}
] |
[
{
"body": "<p>I think B is the best of the three, but here's another alternative using a simple lookup:</p>\n\n<pre><code>middleware.customer = function(req, res, next){\n var methods = {POST: req.body, GET: req.query};\n req.customer = methods[req.method] || false;\n return next();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:43:58.173",
"Id": "39571",
"ParentId": "39568",
"Score": "8"
}
},
{
"body": "<p>The second approach is best because it is the simplest. I would use a ternary conditional to make it clearer that the intention is to assign <em>something</em> to <code>req.customer</code>.</p>\n\n<pre><code>middleware.customer = function(req, res, next){\n req.customer = (req.method == \"POST\") ? req.body :\n (req.method == \"GET\") ? req.query : null;\n return next();\n};\n</code></pre>\n\n<p>I would also put an explicit semicolon to terminate the function definition statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:55:52.967",
"Id": "39572",
"ParentId": "39568",
"Score": "5"
}
},
{
"body": "<p>I keep thinking that you will need this way more than just for <code>customer</code>, and that you should have a function for this so that you keep it DRY.</p>\n\n<p>The tricky thing is naming, how do you call the action of taking either the entire query or the entire body? When would you do this ( only in REST I guess, but even then, what use is POSTing when the entire body only has a customer ID ?, maybe to do an action that only requires the customer ID I guess)</p>\n\n<pre><code>//request.query / request.body represent 1 value, return that value\nfunction getRequestValue( req )\n{\n return (req.method == \"GET\") ? req.query :\n (req.method == \"POST\" ) ? req.body : false; \n}\n\nmiddleware.customer = function(req, res, next)\n{\n req.customer = getRequestValue( req );\n return next();\n}\n</code></pre>\n\n<p>I borrowed some of @200_success here, except that I check for <code>GET</code> first since that should be more common and I return false since that is what you set <code>req.customer</code> initially.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T15:59:07.297",
"Id": "39661",
"ParentId": "39568",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T22:05:09.777",
"Id": "39568",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Functions that return a variable"
}
|
39568
|
<p>I need your help to see if the following binary search code is correct. I did my best to cover the corner cases. I wonder if I missed anything.</p>
<p>The code as it is with tests (you can play with it online <a href="http://www.typescriptlang.org/Playground/" rel="nofollow">here</a>):</p>
<pre><code>function binarySearch<a, r>(
hay: a[],
needle: a,
compare:(one: a, another: a, oneGreaterThanAnother: () => r, oneLessThanAnother: () => r, oneEqualToAnother: () => r) => r,
haveStaightHit: (hay: a[], index: number) => r,
haveExpectedToBeAt: (hay: a[], index: number) => r
) {
if (hay.length > 0) {
return binarySearchUnsafe(hay, needle, 0, hay.length - 1, compare, haveStaightHit, haveExpectedToBeAt);
} else {
return haveExpectedToBeAt(hay, 0);
}
}
function binarySearchUnsafe<a, r>(
hay: a[],
needle: a,
from: number,
to: number,
compare:(one: a, another: a, oneGreaterThanAnother: () => r, oneLessThanAnother: () => r, oneEqualToAnother: () => r) => r,
haveStaightHit: (hay: a[], index: number) => r,
haveExpectedToBeAt: (hay: a[], index: number) => r
): r {
if (from < to) {
var at = from + (~~((to - from) / 2));
return compare(
needle,
hay[at],
function needleIsOnTheRight() {
return binarySearchUnsafe(hay, needle, at + 1, to, compare, haveStaightHit, haveExpectedToBeAt);
},
function needleIsOnTheLeft() {
return binarySearchUnsafe(hay, needle, from, at, compare, haveStaightHit, haveExpectedToBeAt);
},
function needleIsFound() {
return haveStaightHit(hay, at);
}
);
} else if (from > to) {
throw new Error('From index ' + from + ' is bigger than the to index ' + to + '.');
} else {
var at = from /* === to */;
return compare(
needle,
hay[at],
function needleIsOnTheRight() {
return haveExpectedToBeAt(hay, at + 1);
},
function needleIsOnTheLeft() {
return haveExpectedToBeAt(hay, at);
},
function needleIsFound() {
return haveStaightHit(hay, at)
}
);
}
}
function areEqual(actual: any, expected: any) {
if (actual !== expected) throw new Error('Expected: ' + expected + ', Actual: ' + actual);
}
function compareStrings<r>(one: string, another: string, oneGreaterThanAnother: () => r, oneLessThanAnother: () => r, oneEqualToAnother: () => r) : r {
if (one > another) {
return oneGreaterThanAnother();
} else if (one < another) {
return oneLessThanAnother();
} else {
return oneEqualToAnother();
}
}
function failOver(message: string) : any {
return function() {
throw new Error(message);
}
}
try {
binarySearch([], 'x', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 0));
binarySearch(['b', 'd', 'f'], 'b', compareStrings, (hay, index) => areEqual(index, 0), failOver('Direct hit is expected.'));
binarySearch(['b', 'd', 'f'], 'd', compareStrings, (hay, index) => areEqual(index, 1), failOver('Direct hit is expected.'));
binarySearch(['b', 'd', 'f'], 'f', compareStrings, (hay, index) => areEqual(index, 2), failOver('Direct hit is expected.'));
binarySearch(['b', 'd', 'f'], 'g', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 3));
binarySearch(['b', 'd', 'f'], 'a', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 0));
binarySearch(['b', 'd', 'f'], 'c', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 1));
alert('You are all good!');
} catch (e) {
alert(e.message);
}
</code></pre>
|
[] |
[
{
"body": "<p>That looks jolly complicated. If you haven't read it, look for Jon Bentley's <em>Programming Pearls</em> article on binary search. Here's my version:</p>\n\n<pre><code>var bSearch = <T>(xs: T[], x: T, cmp: (p: T, q: T) => number): number => {\n var bot = 0;\n var top = xs.length;\n while (bot < top) { // If x is in xs, it's somewhere in xs[bot..top).\n var mid = Math.floor((bot + top) / 2);\n var c = cmp(xs[mid], x);\n if (c === 0) return mid;\n if (c < 0) bot = mid + 1;\n if (0 < c) top = mid; \n }\n return -1;\n}\n\nvar cmp = (p: number, q: number) => p - q;\n\nconsole.log(bSearch([], 3, cmp) === -1);\nconsole.log(bSearch([3], 3, cmp) === 0);\nconsole.log(bSearch([1, 3], 3, cmp) === 1);\nconsole.log(bSearch([3, 4], 3, cmp) === 0);\nconsole.log(bSearch([3, 3], 3, cmp) !== -1);\nconsole.log(bSearch([1, 2, 3], 3, cmp) === 2);\nconsole.log(bSearch([1, 3, 4], 3, cmp) === 1);\nconsole.log(bSearch([3, 4, 5], 3, cmp) === 0);\nconsole.log(bSearch([4, 5, 6], 3, cmp) === -1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:35:52.533",
"Id": "68853",
"Score": "0",
"body": "Its not complicated, its just in a functional style. If the elemen isn't found my search results to the best expected position, yours always gets -1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:44:41.743",
"Id": "68859",
"Score": "0",
"body": "@bonomo, I'm a well seasoned functional programmer and I'm afraid I don't recognise the functional style in your approach. It would be trivial to rewrite my implementation as a recursive function, if that's what you'd prefer to see. Similarly, one could always return `mid` rather than -1 on failure to indicate a lower bound on where `x` \"should\" be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:57:06.280",
"Id": "68863",
"Score": "0",
"body": "http://en.m.wikibooks.org/wiki/Haskell/YAHT/Type_basics#Continuation_Passing_Style"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:58:45.910",
"Id": "68864",
"Score": "0",
"body": "If you always return mid you would have no way to tell apart a straight hit from a miss."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:20:11.107",
"Id": "68867",
"Score": "0",
"body": "@bonomo, sure you do -- you just look up the item at the returned index. Was it the one you were looking for? Yes: hooray! No: that's where it would go."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:26:08.753",
"Id": "68868",
"Score": "0",
"body": "You would have to document such behavior somewhere, in my approach there is no need for this since it's explicit from usage. Again this is a benefit of using CPS: \"Expressing code in this form makes a number of things explicit which are implicit in direct style.\" From here: http://en.m.wikipedia.org/wiki/Continuation-passing_style"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:29:06.950",
"Id": "68870",
"Score": "0",
"body": "By the way, I understand CPS, I just don't see its benefit here over a more conventional approach. It would be dead easy to change to CPS if that's your preferred option -- I thought your question primarily concerned implementing binary search."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:42:43.873",
"Id": "68876",
"Score": "0",
"body": "I asked to help me to veryfy if my code is correct, there was a bug in it when it alredy got 3 upvotes, you can check tgd history of edits. I hope there are no bugs anymore. There was no other concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:45:00.950",
"Id": "68878",
"Score": "0",
"body": "@bonomo, okey dokey."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T23:35:42.273",
"Id": "40801",
"ParentId": "39573",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T23:37:03.753",
"Id": "39573",
"Score": "2",
"Tags": [
"algorithm",
"binary-search",
"typescript"
],
"Title": "Is this binary search in TypeScript correct?"
}
|
39573
|
<p>The comprehensive description of the problem can be found <a href="http://www.geeksforgeeks.org/median-of-two-sorted-arrays/" rel="nofollow noreferrer">here</a>. I'm looking for code review, clever optimizations, adherence to best practices. etc.</p>
<p>This code is also a correction of code previously posted <a href="https://codereview.stackexchange.com/questions/39560/find-the-median-of-the-combined-data-in-two-input-arrays?noredirect=1#comment66351_39560">here</a>.</p>
<pre><code>/**
* @author javadeveloper
*/
public final class MedianOfTwoSortedArrays {
private MedianOfTwoSortedArrays() {}
private static boolean isMedian (int[] a1, int[] a2, int pos) {
if (pos == 0 || pos == (a1.length - 1)) return true;
return (a1[pos] >= a2[pos]) && (a1[pos] <= a2[pos + 1]);
}
private static double calculateMedian(int[] a1, int a1median, int[] a2, int a2median) {
if (a1median == 0 || a2median == 0 || a1[a2median] < a1[a1median + 1]) return (a1[a1median] + a2[a2median])/2.0;
return ((a1[a1median] + a1[a1median + 1])/2.0);
}
/**
* Given two sorted arrays of same length it returns the median.
* If arrays are not of equal length throws the IllegalArgumentException.
* If arrays are not sorted the results can be unpredictable.
*
* @param a1 the first sorted array
* @param a2 the second sorted array
* @return the median of the two integers or null if no such median is found due to illegal input.
*/
public static Double median (int[] a1, int[] a2) {
if (a1.length != a2.length) throw new IllegalArgumentException("The argument thrown is illegal");
int lb = 0;
int hb = a1.length - 1;
while (lb <= hb) {
int a1Median = (lb + hb)/2;
int a2Median = (a2.length - 1) - a1Median;
// is one of the element constituting the median in first array ?
if (isMedian(a1, a2, a1Median)) {
return calculateMedian(a1, a1Median, a2, a2Median);
}
// is one of the element constituting the median in second array ?
if (isMedian(a2, a1, a2Median)) {
return calculateMedian(a2, a2Median, a1, a1Median);
}
if (a1[a1Median] < a2[a2Median]) {
lb = a1Median + 1;
}
if (a1[a1Median] > a2[a2Median]) {
hb = a1Median - 1;
}
}
return null;
}
public static void main(String[] args) {
int[] a1 = {1, 3, 5, 7, 9};
int[] a2 = {2, 4, 6, 8, 10};
System.out.println("Expected 5.5, Actual " + median (a1, a2));
int[] a3 = {1, 3, 5, 7, 9, 100};
int[] a4 = {2, 4, 6, 8, 10, 200};
System.out.println("Expected 6.5, Actual " + median (a3, a4));
int[] a5 = {1, 2, 3, 4};
int[] a6 = {5, 6, 7, 8};
System.out.println("Expected 4.5, Actual " + median (a5, a6));
int[] a7 = {5, 6, 7, 8};
int[] a8 = {1, 2, 3, 4};
System.out.println("Expected 4.5, Actual " + median (a7, a8));
int[] a9 = {1, 1, 10, 10};
int[] a10 = {5, 5, 5, 5};
System.out.println("Expected 5.0, Actual " + median (a9, a10));
int[] a11 = {5, 5, 5, 5};
int[] a12 = {1, 1, 10, 10};
System.out.println("Expected 5.0, Actual " + median (a11, a12));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T00:51:38.773",
"Id": "66353",
"Score": "2",
"body": "+1 for clear functional specification, and for updating your suite of test cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T18:07:43.330",
"Id": "66414",
"Score": "0",
"body": "Why `isMedian` always true if position is in begining or ending regardless of arrays contents?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:03:37.550",
"Id": "66419",
"Score": "0",
"body": "@ony because arrays are equal sized and sorted. Only case when this happens is a case like [1, 2, 3, 4] and [100, 200, 300, 400]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:14:44.823",
"Id": "66429",
"Score": "0",
"body": "@JavaDeveloper, `isMedian({1,1,3,3}, {2,2,2,2}, 0) == true` - this doesn't look reasonable. Name of function should tell all needed information. If body of that function refers to some context, then name should indicate that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:25:30.110",
"Id": "66431",
"Score": "2",
"body": "It should be noted that this code does not work. Ony has identified that it fails to produce the right answer for the input datasets `{5,5,5,5}` and `{1,1,1,10}`"
}
] |
[
{
"body": "<h2>Short Review</h2>\n\n<p>I have spent some hours trying to understand what you do, and why. Given the mess I made of the previous posting of this question, I thought I should spend extra effort to get this one right.</p>\n\n<p>I have failed. I cannot understand the full intent of your code, and, even though it appears to work, I have this nagging feeling that some well-constructed uses cases will cause the code to fail - you have too many edge-case conditions in the code which are not documented, and not contextualized enough to ascertain whether they work, or what conditions they are supposed to handle.</p>\n\n<p>Bottom line is that your program is not understandable in a reasonable amount of time, and it was your responsibility to make your code understandable, not the reviewer's responsibility to decode your system. Just because you may have your solution 'straight' in your head, it does not mean that you have expressed it well in the code. You have to write and document the code so that someone who has only just seen the problem can understand it and the solution with 'reasonable' effort. In this case, I don't believe you have succeeded.</p>\n\n<h2>Longer Review</h2>\n\n<p>In a 'real' review there is no \"reference implementation\" to compare against. All there is, is a specification. In this case, the specification is to identify the median (middle value, or average of middle-pair if the data-set is even-sized). In addition to the expected result, the data is assumed to be in two equal-sized arrays of sorted data.</p>\n\n<p>Given those specifications you can also make a couple of assumptions:</p>\n\n<ul>\n<li>the ending-dataset will always have an even number of elements (<code>2 * x</code> is always even for any integral value <code>x</code>), which means we will always be doing some form of average.</li>\n<li>There will always be <code>n-1</code> values smaller than the smaller of the mid-point-pair, and <code>n-1</code> values larger than the higher of the mid-point-pair.</li>\n</ul>\n\n<p>OK, based on those specifications and assumptions, we can review the code, and see how it solves the problem.</p>\n\n<ol>\n<li><p>First thing I note is that there are two variables which have names that don't seem to relate to any feature of the problem space, <code>lb</code> and <code>hb</code>. There is no comment to indicate what these variables are, so the only choice is to inspect the code to see how it is used. This means we have to trust that the code is doing the right thing just so we can understand what the intended use of the variable is.</p>\n\n<p>This is a bad practice, and is solved by using <a href=\"http://en.wikipedia.org/wiki/Self-documenting\" rel=\"nofollow noreferrer\">self-documenting variable</a> names. This has <a href=\"https://codereview.stackexchange.com/a/30704/31503\">been pointed out to you before</a>. You need to start improving your code-style.</p></li>\n<li><p>When I try to track down what <code>lb</code> and <code>hb</code> are supposed to be, I find that they are used as a loop condition, which does not help us in this case because the loop condition is not documented. They are also used to calculate the variables <code>a1Median</code> and <code>a2Median</code>. Unfortunately, <code>a1Median</code>, although it is a descriptive name, does not mean what it says it means.... it is <strong>not</strong> the Median of array <code>a1</code>. It starts off being the approximate midpoint of <code>a1</code> (the median is the value at the midpoint, <strong>not</strong> the position of the midpoint), but then, to make things worse, the <code>a1Median</code> is modified in each loop! So, this descriptive variable name has the completely wrong description. This is worse than having a non-descriptive name because, now the person reading the code has to keep remembering that \"a1Median is <strong>not</strong> the median of array a1\"!</p></li>\n</ol>\n\n<p>At this point, in any 'serious' review, you would be facing a lot of criticism. There are times when it is OK for code to be hard to read... but that is only when the problem is very complicated. What you have here is unnecessarily hard to read.</p>\n\n<p>OK, after some study (and I literally mean some serious head-scratching, debugging, and paper-worked examples), I think I can see your algorithm.....</p>\n\n<ul>\n<li>set up <code>lb</code> and <code>hb</code> (still not sure what those are supposed to stand for - low-something and high-something ?) as pointers in to the first array.</li>\n<li>we will manipulate these high and low pointers to select a 'candidate' value in the first array.</li>\n<li>we then use the candidate point in the first array and calculate a candidate point in the second array. The second array's candidate is always going to be where there are n-1 values smaller/larger than the two candidate positions. If our candidate in array1 is <code>x</code> then the candidate in array2 will be <code>array2 - x - 1</code> which would satisfy the midpoint-pair condition.</li>\n<li>if the values at these candidate positions are in fact the midpoints, then we can return a success.</li>\n<li>if we have a success, we do not actually know if the candidate values are in fact the actual pair, all we know is that one of the candidates is the midpoint. The other candidate may not be part of the solution if we have two of the same values on our side... in which case both of the candidates need to come from one array.</li>\n<li>if we do not have a success, we essentually do a 'bifurcation' of the data to do a binary search-style partitioning of the data to look for a candidate.</li>\n</ul>\n\n<p>So, your algorithm has this <code>isMedian()</code> method. Unfortunately, this method re-uses two already bad variable names as parameters. We now have a different <code>a1</code> and <code>a2</code>, which are not the same as the <code>a1</code> and <code>a2</code> in the calling method, because sometimes the calling method swaps the order of these.... Still, this method returns true under conditions which make no apparent sense. Why is there a median when <code>pos == 0</code> ? That seems pretty arbitrary.</p>\n\n<p>This same problem exists in the untangling method <code>calculateMedian()</code>. <code>a1</code> and <code>a2</code> which are not the same as before.</p>\n\n<p>Speaking of untangling, why do you need to untangle? You should not get in to a tangle to start with!</p>\n\n<p>Right, so you have an apparent algorithm, but there are still blanks in what it should be doing, or how it gets it done.</p>\n\n<p>At this point I cheated, and looked at the sample code in the problem description, and your system does <strong>none</strong> of the algorithms.</p>\n\n<p>The first sample algorithm uses naive searching for the median points. Your algorithm does not match that.</p>\n\n<p>The second algorithm uses a reduction-to-size-2 system, and then does a Min/Max formula to get the final result. You do not do this either.</p>\n\n<p>The final algorithm uses recursion and bifurcation. You do not do recursion.</p>\n\n<p>Bottom line is that you are using an algorithm that is hard to read, not comparable to reference systems, and, in the long run, is <strong>not much fun to review</strong>.</p>\n\n<p>Since I do these reviews for my (twisted) satisfaction as well, I can't say that this one was worth it.</p>\n\n<p>Your opening request is:</p>\n\n<blockquote>\n <p>I'm looking for code review, clever optimizations, adherence to best practices. etc.</p>\n</blockquote>\n\n<p>The problem-page you pulled this question from does a perfectly fine job of presenting good code (albeit in C), clever optimizations (that are reproducible in Java quite easily), and the best practices shown there are not great given that it is for C and not Java, but certainly consistent and readable. You have taken those suggestions and ruined them.</p>\n\n<p>Code Review is for reviewing code. I have had to resort to debugging your code just to get a sense of what it does. This is not where code should be when you present it for review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T22:27:13.863",
"Id": "66437",
"Score": "1",
"body": "+1 for suspecting a bug. IRL it may be reasonable to say, \"this doesn't pass my code review (I won't 'sign off' on it) because I haven't been able to satisfy myself that it's correct.\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T06:51:56.700",
"Id": "39584",
"ParentId": "39574",
"Score": "8"
}
},
{
"body": "<p>Isn't it much easier to build two merge iterators that walk from beginning and from end? Move them both together. Once their values match or their orders change (<code>a < b</code> => <code>a > b</code>), you calculate the mean between them.</p>\n\n<p>I believe complexity would be <code>O(n+m)</code> and will work even for non-equally sized arrays.</p>\n\n<p>This solution is much simpler for me:</p>\n\n<pre><code>public final class MedianOfTwoSortedArrays {\n private static final class MergeIterator {\n private final double[] a, b;\n private final boolean forward;\n private int i, j;\n\n public MergeIterator(double[] a, double[] b, boolean forward) {\n this.a = a; this.b = b;\n this.forward = forward;\n if (forward) { i = 0; j = 0; }\n else { i = a.length-1; j = b.length-1; }\n }\n public boolean hasNext() {\n if (forward) return (i < a.length) || (j < b.length);\n else return (i >= 0) || (j >= 0);\n }\n public double next() {\n if (forward) {\n if (j == b.length) return a[i++];\n else if (i == a.length) return b[j++];\n else if (a[i] < b[j]) return a[i++];\n else return b[j++];\n } else {\n if (j < 0) return a[i--];\n else if (i < 0) return b[j--];\n else if (a[i] > b[j]) return a[i--];\n else return b[j--];\n }\n }\n };\n\n public static double median(double[] a, double[] b)\n {\n MergeIterator i = new MergeIterator(a, b, true);\n MergeIterator j = new MergeIterator(a, b, false);\n\n while(true)\n {\n double x = i.next(), y = j.next();\n if (x >= y) return (x+y)/2;\n }\n }\n};\n</code></pre>\n\n<p>Tested with:</p>\n\n<pre><code> double[] a13 = {5, 5, 5, 5};\n double[] a14 = {1, 1, 1, 10};\n // 1, 1, 1, 5, 5, 5, 5, 10\n System.out.println(\"Expected 5.0, Actual \" + median (a13, a14));\n</code></pre>\n\n<p>Original code gives <code>7.5</code> while this gives <code>5.0</code>.</p>\n\n<p><em>Updated:</em> fixed <code>MergeIterator</code> for backward walk</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T08:01:36.810",
"Id": "66377",
"Score": "0",
"body": "Its an interview question, and main objective here is to reduce complexity to logarithmic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T22:00:50.017",
"Id": "66435",
"Score": "0",
"body": "`Original code gives 7.5` Confirmed. +1 for finding another bug."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T07:44:07.913",
"Id": "39585",
"ParentId": "39574",
"Score": "5"
}
},
{
"body": "<p>You could have better testing to ensure your code is correct. I like to verify whether code is correct via code inspection, but sometimes the code is complicated enough that it's difficult to be sure.</p>\n\n<p>You have test cases, which is good, and you add to your test cases when you find a bug: also good.</p>\n\n<p>Two problems with your existing test cases are:</p>\n\n<ul>\n<li><p>You have written the input data by hand, yourself; so you test cases only include data which you have thought of. However the code might fail if it is given some data which you haven't thought of.</p></li>\n<li><p>You calculate the 'expected result' in your head, and add it to the test case. That makes it difficult to run 100s or 1000s of possible test cases.</p></li>\n</ul>\n\n<p>Possible solutions:</p>\n\n<ul>\n<li><p>If you have a new or tricky implementation, you may be able to test it against a <a href=\"http://en.wikipedia.org/wiki/Reference_implementation\" rel=\"nofollow\">reference implementation</a>. For example when people write a TCP/IP stack, they would test it for interoperability with other, existing, 'known-good' implementations. For this problem, you could either:</p>\n\n<ul>\n<li>Choose one the 'reference implementations' from <a href=\"http://www.geeksforgeeks.org/median-of-two-sorted-arrays/\" rel=\"nofollow\">there</a></li>\n<li>Write an easy-to-verify implementation: for example, concatenate the two arrays into a third 'target' array, sort the 'target' array, and return the median of the target array: which, you could do in about 3 lines of code, simple enough to verify by inspection.</li>\n</ul>\n\n<p>Your test suite could then compare output from your code-to-be-tested with the output from your 'known-good' implementation.</p></li>\n<li>Think about how to get better 'coverage' of your input data; for example:\n<ul>\n<li>Edge cases (input data which contain <code>0</code>, or <code>int.MaxValue</code>, or repeating/identical values)</li>\n<li>Illegal cases (unsorted input, arrays of different lengths) <-- not applicable to this problem</li>\n<li>Random input (generate the sorted numbers randomly, so that it tests data you haven't even thought of)</li>\n<li>Complete coverage (test every possible combination of sorted numbers, for arrays of length 2, 3, and 4)</li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T12:08:26.990",
"Id": "39589",
"ParentId": "39574",
"Score": "5"
}
},
{
"body": "<p>Ok. Lets try to solve it with logarithmic complexity. I'm not sure that having equal sizes can help much except that we always expect even length. But I agree that we can achieve <code>O(log(n))</code>. I'll try to follow idea of your code (hope I were able to guess it).</p>\n\n<p>We know that median would divide two arrays into four parts with indexes that:</p>\n\n<ul>\n<li><code>a[i-1] <= b[j] && a[i] >= b[j-1]</code><br>\nYep, values in lower parts (for both arrays) should be less than values in upper parts.<br>\nOur <code>i</code> says that indexes <code>[0;i)</code> is lower part of <code>a</code> and <code>[i;n)</code> is upper. Thus we compare last value from lower with first value from upper.</li>\n<li><code>i + j == (a.length - i) + (b.length - j)</code> => <code>j = a.length - i</code><br>\nThat's looks sane. If we split first array into <code>n</code> of lower values and <code>m</code> upper values we should split second array into <code>m</code> lower values and <code>n</code> upper values to get equal amount of values in upper and lower parts.</li>\n<li>if we'll consider situation without restriction on equal sizes we'll need to be prepeared for situation when in one of array we'll have index of element and other will have division in two parts.</li>\n<li>its easier to think that:<br>\n<code>i = 0</code> means <code>{ | 1, 2, 3, 4} { 5, 6, 7, 8 | }</code> (<code>j = 4</code>)<br>\n<code>i = 2</code> means <code>{1, 3 | 5, 7} {0, 2 | 4, 8}</code> (<code>j = 2</code>). </li>\n</ul>\n\n<p>For simplicity I'll consider only <code>n % 2 == 0</code> variant:</p>\n\n<pre><code>private static final class MedianLookup {\n private final int[] a, b;\n\n MedianLookup(int[] a, int[] b)\n {\n assert (a.length % 2) == 0; // TODO: other case\n assert a.length == b.length;\n this.a = a; this.b = b;\n }\n}\n</code></pre>\n\n<p>Lets define our check function:</p>\n\n<pre><code> private int cmpMedian(int i)\n {\n // i + j == (a.length - i) + (b.length - j)\n // 2*j == a.length + b.length - 2*i\n int j = a.length - i;\n\n // a[i-1] <= b[j] && a[i] > b[j-1]\n double lb1 = i == 0\n ? Double.NEGATIVE_INFINITY\n : a[i-1];\n double ub1 = i == a.length\n ? Double.POSITIVE_INFINITY\n : a[i];\n double lb2 = j == 0\n ? Double.NEGATIVE_INFINITY\n : b[j-1];\n double ub2 = j == b.length\n ? Double.POSITIVE_INFINITY\n : b[j];\n if (lb2 > ub1) return +1; // need to incr index\n else if (lb1 > ub2) return -1; // nedd to decr index\n else return 0;\n }\n</code></pre>\n\n<p>And lookup will look like:</p>\n\n<pre><code> public double lookup()\n {\n int lb = 0, ub = a.length;\n while (lb <= ub)\n {\n int i = (lb + ub)/2;\n int answ = cmpMedian(i);\n if (answ < 0) ub = i-1;\n else if (answ > 0) lb = i+1;\n else return calculateMedian(i);\n }\n return Double.NaN;\n }\n</code></pre>\n\n<p>Calculate median may look a bit more complex:</p>\n\n<pre><code> private double calculateMedian(int i)\n {\n int j = a.length - i;\n\n // simple cases when arrays can be attached one to other\n if (i == 0) // b <-> a\n { return (b[j - 1] + a[0])/2.0; }\n else if (j == 0) // a <-> b\n { return (a[i - 1] + b[0])/2.0; }\n\n // overlapping (search best pair)\n double lb1 = a[i-1], ub1 = a[i];\n double lb2 = b[j-1], ub2 = b[j];\n double bestSum = lb1 + ub1,\n bestDiff = ub1 - lb1;\n if ((ub2 - lb1) < bestDiff)\n { bestSum = ub2+lb1; bestDiff = ub2-lb1; }\n if ((ub1 - lb2) < bestDiff)\n { bestSum = ub1+lb2; bestDiff = ub1-lb2; }\n if ((ub2 - lb2) < bestDiff)\n { bestSum = ub2+lb2; bestDiff = ub2-lb2; }\n\n return bestSum/2;\n }\n</code></pre>\n\n<p><em>Updated:</em> too many hours with Haskell language. Found integer devision in <code>calculateMedian()</code> for simple cases.</p>\n\n<p>Now I get:</p>\n\n<pre><code>Expected 5.5, Actual 5.5\nExpected 6.5, Actual 6.5\nExpected 4.5, Actual 4.5\nExpected 4.5, Actual 4.5\nExpected 5.0, Actual 5.0\nExpected 5.0, Actual 5.0\nExpected 5.0, Actual 5.0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:05:58.083",
"Id": "39616",
"ParentId": "39574",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39616",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T00:33:32.923",
"Id": "39574",
"Score": "3",
"Tags": [
"java",
"array",
"binary-search"
],
"Title": "Median of two sorted equal sized arrays on combination"
}
|
39574
|
<p>I'm writing a utility that validates fields. I decided to try my hand at <a href="http://en.wikipedia.org/wiki/Behavior-driven_development" rel="nofollow">Behaviour Driven Development (BDD)</a>. The validator utilises "rules" to determine if field is valid.</p>
<p>Three different types of rules exist:</p>
<ol>
<li><code>RegexRule</code> A field conforms to specific pattern(s)</li>
<li><code>RequireRule</code> A value is present</li>
<li><code>EqualityRule</code> A field's value equals another's value</li>
</ol>
<p>A rule is tested against a value. If the value does not conform to the rule, a flag is set which marks the rule as erroneous. Calling <code>getError()</code> on an erroneous rule returns a string that details the error. Furthermore, the rule is reset (no longer erroneous).</p>
<p>Is this the correct manner of implementing BDD on this class? I'd greatly appreciate advice on how I could improve on this.</p>
<pre><code>describe('RequireRule', function() {
var nameErr = 'The name field is required';
beforeEach(function() {
this.r = new RequireRule('name', nameErr);
});
describe('test()', function() {
it('should return false when value provided is null or undefined', function() {
expect(this.r.test('asd')).to.equal(true);
});
it('should return true when value provided is not null or undefined', function() {
expect(this.r.test(null)).to.equal(false);
});
});
describe('isErroneous()', function() {
it('should become erroneous when value tested is null or undefined', function() {
r.test(null);
expect(this.r.isErroneous()).to.equal(true);
});
it('should not be erroneous when value tested is not null or undefined', function() {
r.test('asd');
expect(this.r.isErroneous()).to.equal(false);
});
});
describe('getError()', function() {
it('should return null when the test() succeeded', function() {
r.test('asd');
expect(this.r.getError()).to.equal(null);
});
it('should return the error string when the test() failed, and set erroneous to false', function() {
r.test(null);
expect(this.r.getError()).to.equal(nameErr);
expect(this.r.isErroneous()).to.equal(false);
});
});
});
</code></pre>
<p>The test framework is <a href="http://visionmedia.github.io/mocha/" rel="nofollow">Mocha</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T06:59:09.860",
"Id": "66375",
"Score": "0",
"body": "What assertion & test running framework are you using? I don't know if I need to know or not yet, but I would hate to be like \"yeah, everything looks great!\" and miss a really obvious error or quirk that spoils the whole thing while I assume everything just does what it looks like it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T08:25:57.247",
"Id": "66382",
"Score": "0",
"body": "The two `test()` expectations are reversed from their descriptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T08:36:03.723",
"Id": "66383",
"Score": "0",
"body": "[link](http://visionmedia.github.io/mocha/) Mocha"
}
] |
[
{
"body": "<p>Let me say up front that I'm far more familiar with <em>unit</em> testing than <em>behavior</em> testing, but this looks an awful like you wrote the tests after the code. When I think of \"behavior\", I don't think of neatly mapping it to method names. Instead I would write use cases that may require multiple method calls.</p>\n\n<blockquote>\n <p><strong>Note:</strong> I don't recall seeing nested <code>describe</code> blocks before, but I assume whatever testing framework (Jasmine?) handles this neatly and that <code>beforeEach</code> is called with every <code>it</code> call.</p>\n</blockquote>\n\n<p>The following rewrite tests only the error (<code>null</code> value provided) path to make it easier to follow. The main difference is that each test now checks a single aspect of the overall behavior. You still need to decide how to group the tests for each use case--either with separate top-level <code>describe</code> blocks or nesting as you did above.</p>\n\n<pre><code>describe('RequireRule', function() {\n var nameErr = 'The name field is required';\n\n beforeEach(function() {\n this.r = new RequireRule('name', nameErr);\n });\n\n it('should return false to denote an error', function() {\n expect(this.r.test(null)).to.equal(false);\n });\n\n it('should set erroneous to true to denote an error', function() {\n this.r.test(null);\n expect(this.r.isErroneous()).to.equal(true);\n });\n\n it('should return the message when erroneous', function() {\n this.r.test(null);\n expect(this.r.getError()).to.equal(nameErr);\n });\n\n it('should clear the message after reading the message', function() {\n this.r.test(null);\n this.r.getError();\n expect(this.r.getError()).to.equal(null);\n });\n\n it('should set erroneous to false after reading the message', function() {\n this.r.test(null);\n this.r.getError();\n expect(this.r.isErroneous()).to.equal(false);\n });\n});\n</code></pre>\n\n<p>I find that I naturally tend toward structuring my unit tests like this when I write them first using TDD. I imagine BDD would have the same effect. This results in tests that apply to the class as a whole rather than picking apart each method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T10:01:25.843",
"Id": "66384",
"Score": "0",
"body": "Say, for example, I had another Rule I wanted to test these BDD tests on (not just 'r'). How should I go about repeating these without repeating code? I think a loop would work, but it's probably not the most elegant solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:46:26.493",
"Id": "66428",
"Score": "0",
"body": "The problem with getting tricky in tests is that test code is untested. Each test needs to be obviously correct from a cursory visual inspection. That being said, I am not against some basic DRY techniques such as a function containing the above specs: `function it_should_treat_null_as_error(rule)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T08:24:20.067",
"Id": "39588",
"ParentId": "39576",
"Score": "2"
}
},
{
"body": "<p>This is <em>roughly</em> what BDD should look like. You're definitely on the right track in that you have a specific set of postconditions and expected results for every \"public\" method. However, the tests for these postconditions are incomplete in some respects that I think will probably come up as edge conditions and/or browser quirks (assuming your system is going to run in a browser). In addition, you're testing behaviors in this suite that are shared between your subclasses - even if they don't actually share a <code>prototype</code>, they do have a common interface and common expectations.</p>\n\n<p>For incompleteness, I'm referring to 'should return false when value provided is null <strong>or undefined</strong>' when the corresponding test only tests <code>null</code>. This should be two tests, one for <code>null</code> and another for <code>undefined</code>. In addition, you should define and test the function's behavior for other values that are commonly mistaken for <code>null</code> and <code>undefined</code>, like <code>0</code>, <code>false</code>, and <code>''</code>. The empty string is of particular importance because it's unclear from your tests whether an empty string is acceptable as long as it's specified - the source of your data might determine whether that's applicable. I would go with two or three tests per native type: one that is acceptable, one that is not (if both are applicable), and one that is falsy (if the falsy value for the type is not already covered). If you <em>really</em> want to go all out, define behavior for the parameters <code>'0'</code>, <code>'false'</code>, <code>'undefined'</code>, and <code>NaN</code>.</p>\n\n<p>This sounds like a pain to do - especially when you see that you need to define said behavior for all of the other functions whose preconditions are the same. The root of the problem here is that your preconditions are not very DRY. Each function has two test cases: <code>null</code> and <code>'asd'</code> as inputs to <code>test</code>. Since <code>null</code> and <code>'asd'</code> are not really the only two inputs you can expect to get, your tests shouldn't be coupled to those two inputs. Further, when you go to write your tests for your other rule subclasses, you will be unable to re-use your <code>isErroneous</code> and <code>getError</code> tests because they have specifically named <code>null</code> as erroneous and <code>'asd'</code> as acceptable.</p>\n\n<p>I'm not a mocha expert, so I don't know how helpful or cooperative it will be, but you can refactor your suites to test <em>states</em> rather than classes, and it will be far DRYer. From what I can tell, the rule subclasses <em>all</em> have the following features:</p>\n\n<ul>\n<li>A (theoretically unbounded) set of inputs to the <code>test</code> method that will:\n<ul>\n<li>return <code>false</code></li>\n<li>leave the object in an erroneous state</li>\n</ul></li>\n<li>A (theoretically unbounded) set of inputs to the <code>test</code> method that will:\n<ul>\n<li>return <code>true</code></li>\n<li>leave the object in a validated state</li>\n</ul></li>\n<li>An initial state before <code>test</code> is ever called, whose behavior remains unspecified.</li>\n</ul>\n\n<p>Each of your subclasses has a different set of erroneous and valid inputs, but you can easily define the behavior of those three states independently:</p>\n\n<ul>\n<li>A rule object in an erroneous state should:\n<ul>\n<li>return <code>true</code> from <code>isErroneous()</code></li>\n<li>return non-<code>null</code> from <code>getError()</code></li>\n<li>(become | not become) valid when a valid input is provided to <code>test</code></li>\n</ul></li>\n<li>A rule object in a validated state should:\n<ul>\n<li>return <code>false</code> from <code>isErroneous()</code></li>\n<li>return <code>null</code> from <code>getError()</code></li>\n<li>(become | not become) erroneous when an invalid input is provided to <code>test</code></li>\n</ul></li>\n<li>A rule object in its initial state should:\n<ul>\n<li>probably have defined behavior for <code>getError</code> and <code>isErroneous</code>, too.</li>\n<li>become valid when a valid input is provided to <code>test</code></li>\n<li>become erroneous when an invalid input is provided to <code>test</code></li>\n</ul></li>\n</ul>\n\n<p>Now, your tests for all of your classes are reduced to the task of generating the input test cases and expected states they will generate. For the <code>RequiredRule</code>, that could be easily expressed in two arrays; you might want something different for your more complicated rules, since the criteria are presumably individualized per object for those subclasses. I might go with something like a generator.</p>\n\n<p>The concept of a class is helpful for BDD when you have specific class invariants, but with javascript you are by no means limited to a one-to-one correspondence between a class (constructor/prototype) and its defined behaviors. Like anything else in software design, you can tell your unit test is wrong as soon as you type the same thing 2 or 3 times. Usually, you can fix the repetition by making the object of your suite (parameter to <code>describe</code>) something more applicable than the name of the constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T00:21:36.767",
"Id": "67021",
"Score": "0",
"body": "I haven't written the tester class as yet, but does this correctly reflect your response? http://pastebin.com/ADB9meHV"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T02:22:47.197",
"Id": "67030",
"Score": "0",
"body": "Perfect so far!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T00:43:06.320",
"Id": "39773",
"ParentId": "39576",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T01:57:41.617",
"Id": "39576",
"Score": "7",
"Tags": [
"javascript",
"unit-testing",
"validation",
"bdd",
"mocha"
],
"Title": "Am I implementing BDD correctly?"
}
|
39576
|
<p>I created a rubber ball by extending instance of b2Body prototype of Box2D.js. I get the instance from factory method <code>b2World#CreateBody</code>.</p>
<pre><code>var ball = world.CreateBody(bodyDef);
</code></pre>
<p>I extended the instance in the constructor of my RubberBall prototype. In result, I made the constructor very long. </p>
<pre><code>function RubberBall(position) {
var ball = world.CreateBody(bodyDef);
:
:
very long implementation to extend `ball` to make it a rubber ball
}
</code></pre>
<p>How can I extract the extending <code>ball</code> part and make the constructor simple?</p>
<p><a href="http://jsfiddle.net/suzuki/XXmeR/" rel="nofollow">http://jsfiddle.net/suzuki/XXmeR/</a></p>
|
[] |
[
{
"body": "<h1>Prototypal Inheritance</h1>\n<p>Now, the very first problem you'll face in your implementation is memory usage. Each <code>RubberBall</code> instance will be creating an internal function - that's a bad thing:</p>\n<pre><code>function RubberBall(){\n this.someFn = function(){...}\n}\n</code></pre>\n<p>In this sample code above, each <code>RubberBall</code> instance will create its own <code>someFn</code>. Functions are also objects in JS and will take up memory.</p>\n<p>The proper way to do it in JS is to place those methods in the prototype, so that they are shared in all instances of <code>RubberBall</code>. This is what we call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain\" rel=\"nofollow noreferrer\">prototypal inheritance</a> Do note that we are only placing/sharing the methods. Instance data remains in the instance:</p>\n<pre><code>function RubberBall(){\n // ballData gets created *per instance*\n this.ballData = 'I am bouncy';\n}\n\n// Assign a prototype object, shared accross all instances of RubberBall\nRubberBall.prototype = {\n getData : function(){\n // If called as `[instance].getData()`, `this` is the instance.\n return this.ballData;\n }\n}\n</code></pre>\n<p>As far as I've read (but I may be wrong), the V8 engine optimizes objects via hidden classes, and are more optimized if you declare all instance properties in advance. That way, it does not do some "run-time rebuilding". So have your rubber ball properties declared in advance.</p>\n<p>Now, you wanted to extend Box2D's <code>b2Body</code> (I'm not well versed in Box2D so pardon my vocabulary). The previous example does not yet inherit it. So [we use the more proper <code>Object.create][2]</code> to create an object that has <code>b2Body</code> in its prototype. Let's modify the previous example:</p>\n<pre><code>function RubberBall(){\n // Attach to this instance all properties of b2Body\n b2Body.call(this);\n\n this.ballData = 'I am bouncy';\n}\n\n// Now create our prototype object, with its prototype pointing to b2Body's prototype\nRubberBall.prototype = Object.create(b2Body.prototype);\n\n// Then attach methods to it\nRubberBall.prototype.getData = function(){...} \nRubberBall.prototype.anotherSharedMethod = function(){...}\n</code></pre>\n<h2>Private members</h2>\n<p>JS wasn't designed to have private members, but there are a lot of ways to emulate it (and I think ES6 has something more formal for it). You can create closures, which are fast, but if not handled properly, might eat memory.</p>\n<p>So let's stick to prototypal inheritance and public members. If you need to indicate that it's private, by convention you can prefix the property or method with a <code>_</code>.</p>\n<h1><code>requestAnimationFrame</code></h1>\n<p>Modern browsers are now equipped with <a href=\"https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame\" rel=\"nofollow noreferrer\"><code>requestAnimationFrame</code></a> which is a special timer that executes a given function as fast as possible, aiming 60fps. It's also optimized to throttle it's speed in different situations, like slowing down when the tab is not focused to save battery.</p>\n<p><a href=\"http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/\" rel=\"nofollow noreferrer\">There are polyfills</a> that automatically fill in the gap, especially for older browsers that don't have it.</p>\n<h1>Standard Reminders</h1>\n<ul>\n<li>Don't use globals</li>\n<li>Place everything you do in a namespace or an enclosed scope</li>\n<li>Keep your code short and readable</li>\n<li>Use proper indentation</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T16:10:08.040",
"Id": "66401",
"Score": "0",
"body": "Thank you very much @Joseph! requestAnimation, call() and Object.create were new to me.\n\n\nHere's my refined code where the advice you gave me worked perfectly! note I found I should extend `b2CircleShape` rather than `b2Body` afterward and did so.\n\nhttp://jsfiddle.net/suzuki/79yse/4/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T05:50:38.050",
"Id": "39582",
"ParentId": "39578",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T03:51:21.070",
"Id": "39578",
"Score": "3",
"Tags": [
"javascript",
"prototypal-class-design",
"factory-method"
],
"Title": "Extending prototype of given instance from factory method"
}
|
39578
|
<p>Critiques (even pedantic ones) are welcome.</p>
<pre><code>bool unique_chars(std::string &s) {
if (s.length()>256) return false;
std::bitset<256> bs;
for (auto &c:s) {
if (bs.test(c)) return false;
bs.set(c);
}
return true;
}
</code></pre>
<p><strong>EDIT 1:</strong></p>
<pre><code>for (auto &c:s) { //OLD
for (unsigned char c:s) { //NEW
</code></pre>
<p>Reasoning:</p>
<ol>
<li><code>char</code> can be either signed or unsigned</li>
<li>if signed then <code>bs[]</code> can be out of bounds</li>
<li>casting to unsigned eliminates issue as negative values will wrap</li>
</ol>
<p><strong>EDIT 2:</strong></p>
<p>This string is to be made up of characters from the standard ASCII character set, i.e. fitting into a 1 byte <code>char</code>.</p>
<p><strong>EDIT 3:</strong></p>
<p>Renamed function / added test harness with examples. Function parameter changed to const, as string not being modified.</p>
<pre><code>#include <iostream>
#include <bitset>
bool areCharsUnique(const std::string &s) {
if (s.length()>256) return false;
std::bitset<256> bs;
for (unsigned char c:s) {
if (bs.test(c)) return false;
bs.set(c);
}
return true;
}
int main() {
std::string s1 = "hi there";
std::string s2 = "hey man";
std::cout << areCharsUnique(s1) << std::endl; //0
std::cout << areCharsUnique(s2) << std::endl; //1
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>That's pretty good. It's short. The early returns communicate intent well, and since the function is short, they don't get lost. Formatting is good, and the variable names, although very short, are common abbreveviations that work well here.</p>\n\n<p>I'd consider making the argument <code>const</code>, since it's not modified by the function.</p>\n\n<p>I've been out of C++ a long time, so I might be missing something here, but I'd consider <code>auto c:s</code> instead of <code>auto &c:s</code>. I can't see a reason to work with a reference when a character is cheap to copy.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T05:40:42.253",
"Id": "39581",
"ParentId": "39579",
"Score": "8"
}
},
{
"body": "<p>@Wayne Conrad has made some good points. I just have a few additional ones:</p>\n\n<ul>\n<li><p>I'm not sure about checking against a maximum value, but I'll address it anyway.</p>\n\n<p>In case you'd like to change the default <code>256</code>, consider having a <code>template</code> parameter. That way, the value can be changed at just one location. It'll also give more meaning to that value.</p>\n\n<pre><code>template <std::size_t maxChars = 256>\nbool unique_chars(std::string &s) {\n if (s.length() > maxChars) return false;\n std::bitset<maxChars> bs;\n\n // ...\n}\n</code></pre></li>\n<li><p>To slightly add on to Wayne's point about <code>const</code>, make sure the argument is <code>const&</code> so that no unnecessary copying is done. In addition, declaring the string argument as <code>const</code> will allow it to be passed in while avoiding casting.</p></li>\n<li><p>Consider renaming the function to something like <code>areUniqueChars()</code>. Otherwise, it may sound like it's returning the <em>number</em> of unique chars.</p></li>\n<li><p>In C++, prefer to put unary operators (such as <code>&</code> and <code>*</code>) next to the type:</p>\n\n<pre><code>std::string& s;\n</code></pre>\n\n<p></p>\n\n<pre><code>for (auto& c : s) {}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T03:58:40.560",
"Id": "66621",
"Score": "2",
"body": "It might be more accurate to say that declaring the argument `const` allows `const` strings to be passed in without nasty casting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T05:57:43.727",
"Id": "39583",
"ParentId": "39579",
"Score": "10"
}
},
{
"body": "<p>One theoretical place that this code might fail is when the string contains multibyte characters. </p>\n\n<p>For example UTF-8 encoding is being used and string passed to the function is \"€Abبώиב¥£€¢₡₢₣₤₥₦§₧₨₩₪₫₭₮漢Ä©óíßä\" although no character is being repeated, the function will return true.</p>\n\n<p>But handling this case is not straight forward at all, as standard library doesn't provide any way to iterate over actual characters in a string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T12:31:06.320",
"Id": "39590",
"ParentId": "39579",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p>Critiques (even pedantic ones) are welcome.</p>\n</blockquote>\n\n<p>There's no 'functional specification' included with your question, there is just the code. <a href=\"https://codereview.meta.stackexchange.com/a/76/34757\">You should include a functional specification</a>, a.k.a. \"the problem\" to be solved, or \"the requirements\". Without one, we can see what the code does, but cannot assess whether what it does matches what it is required .</p>\n\n<p>If the (missing) functional specification said, \"string\", then perhaps it doesn't mean only <code>std::string</code> ... for example, it might also mean <code>std::wstring</code>.</p>\n\n<p>If so then your unique_chars should be a template function (in the same way that <code>std::basic_string</code> is a template class).</p>\n\n<p>If you were working with very wide multi-byte characters (e.g. <code>std::char32_t</code>) you would prefer <code>std::set</code> or <code>std::unordered_set</code> (a hash set) instead of a <code>std::bitset</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T15:12:38.313",
"Id": "39595",
"ParentId": "39579",
"Score": "10"
}
},
{
"body": "<p>Here's a two-line solution using some of the standard algorithms: first <code>sort</code> a copy of the string, then use <code>adjacent_find</code> to determine if any adjacent characters are identical. If there aren't, <code>adjacent_find</code> will return the <code>end()</code> iterator of the string copy, so you simply compare against that</p>\n\n<pre><code>bool areCharsUnique(std::string s) \n{\n std::sort(begin(s), end(s));\n return std::adjacent_find(begin(s), end(s)) == end(s);\n}\n</code></pre>\n\n<p>Note that the function takes its argument by-value, which allows also temporaries as arguments. As pointed out by @ChrisW in the comments, you could also use <code>const&</code> as argument but then you would need an extra copy in order to be able to sort.</p>\n\n<p>It works on strings of any length and for any character set.</p>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/1dd914b70732e987\" rel=\"nofollow\"><strong>Live Example</strong></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T10:29:06.390",
"Id": "66889",
"Score": "0",
"body": "+1 If the argument were a const reference (not a non-const reference), that too would permit temporaries as arguments. The main reason for passing by value (making a copy) is that you mutate the contents of `s` so you probably should mutate a copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T10:31:01.113",
"Id": "66890",
"Score": "0",
"body": "@ChrisW agreed yes, although I didn't want to go into detail about move semantics and such. The alternative would be to have two overloads: `const&` and `&&`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T10:32:02.353",
"Id": "66891",
"Score": "0",
"body": "I don't think the OP has a keyhole problem: it handles strings of greater than 256, it just [handles them efficiently by assuming/knowing that they must contain duplicates](http://codereview.stackexchange.com/questions/39579/testing-whether-characters-of-a-string-are-unique/39868#comment66397_39579). You could remove the `if (s.length()>256) return false;` and it would still behave correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T10:35:25.280",
"Id": "66892",
"Score": "0",
"body": "@ChrisW tnx for pointing that out. I still wonder about the 256 wide character set that this implies. My solution should work even for wide character sets (obviously it would need another overload for `wstring`)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T10:13:34.670",
"Id": "39868",
"ParentId": "39579",
"Score": "5"
}
},
{
"body": "<p>Good code.</p>\n\n<p>Consider converting a <code>const std::string&</code> parameter into an iterator pair: no reason to not support <code>std::vector<unsigned char></code>, <code>std::deque</code>-s, etc. You could add a template helper function to have the code run when passed a string <code>s</code> itself, not <code>begin(s), end(s)</code>.</p>\n\n<p>On a pedantic note, if you are eager to try fancy things: I would allow non-one-byte inputs, but add an assertions that all the values are in the range [0 .. 256) when unsigned. You could do it using type traits (or by analyzing sizeof(T) at compile time). Basically, if an input is a string/array/container/range of elements of type of <code>sizeof(T) == 1</code>, you need to do nothing else, while if the input is a bunch of <code>int</code>-s, you may want to assert or throw an exception what/if any of the input \"characters\" is outside this range.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T18:48:01.480",
"Id": "39901",
"ParentId": "39579",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39583",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T05:19:03.220",
"Id": "39579",
"Score": "18",
"Tags": [
"c++",
"algorithm",
"strings",
"c++11"
],
"Title": "Testing whether characters of a string are unique"
}
|
39579
|
<p>In this program, I understood everything except <code>power(x1,y1-1)</code>. I want to know how the <code>power(x1,y1-1)</code> function exactly works.</p>
<pre><code> #include<iostream.h>
#include<conio.h>
int power(int,int);
void main()
{
int x,y,p;
clrscr();
cout<<"\n\n\t calculating power of a number using recursion";
cout<<"\n\n\t Enter base ";
cin>>x;
cout<<"\n\n\t enter index";
cin>>y;
if(y==0)
{
cout<<"\n\n\tpower is 1";
}
if(y<0)
{
y=y*(-1);
p=power(x,y);
cout<<"\n\n\t power is"<<1/p;
}
p=power(x,y);
cout<<"\n\n\t the power is"<<p;
getch();
}
int power(int x1,int y1)
{
if(y1==1)
return(x1);
else
return(x1*power(x1,y1-1));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T13:29:59.233",
"Id": "66389",
"Score": "0",
"body": "Please fix indentations of your program. It is very hard to read code without proper indentations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T13:47:08.583",
"Id": "66391",
"Score": "0",
"body": "fixing indentation not mean add empty line between every line. I have fixed it for you. Next time you will know what it is mean by this phrase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T13:47:51.773",
"Id": "66392",
"Score": "5",
"body": "This question appears to be off-topic because it is about code that is not your own. If you do not understand how the recursion works then you could not have written this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T13:53:36.120",
"Id": "66393",
"Score": "0",
"body": "Thanks. Actually i executed this code during practical in my college. But im really confused with this power function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T14:43:42.753",
"Id": "66396",
"Score": "0",
"body": "There are plenty of things I did in college that I have forgotten. Don't ask me for examples, though: I forget what."
}
] |
[
{
"body": "<p>The laws of recursion are:</p>\n\n<ol>\n<li>Change at least one argument while recurring. The arguments must be changed to be closer to termination</li>\n<li>The changing argument must be tested in the termination condition</li>\n</ol>\n\n<p>(from <a href=\"http://rads.stackoverflow.com/amzn/click/0262560992\" rel=\"nofollow\">The Little Schemer</a>, a most excellent book about recursion)</p>\n\n<p>The <code>y1-1</code> in this line takes care of rule 1:</p>\n\n<pre><code>return(x1*power(x1,y1-1));\n</code></pre>\n\n<p>and this line takes care of rule 2:</p>\n\n<pre><code>if(y1==1)\n</code></pre>\n\n<p>Each time the function calls itself, it decrements y1. When y1 reaches 1, the function is done.</p>\n\n<p>(You may also note that if y1 is less than 1, the function will not work correctly: mathematically, it will loop forever, but in actuality, on most architectures y1 will underflow, become positive, and eventually reach 1, at which point the function will return a wildly incorrect result).</p>\n\n<p>It would be instructive to execute this function in your head--pretend to be the computer. Call the function with x1 = 2 and y1 = 3 and step through it, doing everything the computer would do. Use a pencil and a piece of paper to keep track of the values of x1 and y1, remembering that each recursive call creates a new stack frame with new, independent values of x1 and y2; each return destroys the most recent stack frame and restores x1 and x2 to the values they had in the previous stack frame.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T14:39:52.627",
"Id": "66395",
"Score": "1",
"body": "\" Use a pencil and a piece of paper to keep track of the values of x1 and y1, remembering that each recursive call creates a new stack frame with new, independent values of x1 and y2; each return destroys the most recent stack frame and restores x1 and x2 to the values they had in the previous stack frame.\" really worked .Thanks a lot !!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T14:09:39.890",
"Id": "39594",
"ParentId": "39591",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39594",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T13:05:32.357",
"Id": "39591",
"Score": "-2",
"Tags": [
"c++",
"recursion"
],
"Title": "Recursively calculating powers of numbers"
}
|
39591
|
<p>My program uses graphics convolution, an algorithm that processes pixels to make them round, soft and blurred. This particular algorithm is well-known, but its slowing down the operation of the whole program.</p>
<p>Can you suggest any improvements of this algorithm? I tried following from <a href="https://stackoverflow.com/questions/98359">here</a>, especially "ultimate solution" all the way to the bottom of that page, hoping to reduce the number of for loops one within another, but it did not work.</p>
<pre><code>import perceptron.DoubleBuffer.ImageRenderContext;
import util.ColorUtility;
import java.awt.image.DataBuffer;
public final class Convolution {
DoubleBuffer buffer;
int[] d;
int s, h, e;
int[] temp;
/**
* Constructs new Convolution using the convolution degree and DoubleBuffer as input parameters.
*
* @param std
* @param b
*/
public Convolution(int std, DoubleBuffer b) {
s = 2 * std;
h = s / 2;
e = 256 / h;
d = new int[s];
buffer = b;
for (int i = 0; i < s; i++) {
d[i] = (int) (256 * gaussian(i - s / 2, std));
}
temp = new int[b.buffer.W * b.buffer.H];
}
/**
* Optimized power function. Poor quality?
*/
public static double power(final double a, final double b) {
final long tmp = (Double.doubleToLongBits(a) >> 32);
final long tmp2 = (long) (b * (tmp - 1072632447) + 1072632447);
return Double.longBitsToDouble(tmp2 << 32);
}
/**
* Optimized exponent function with little benefit.
*/
public static double exponent(double val) {
final long tmp = (long) (1512775 * val + (1072693248 - 60801));
return Double.longBitsToDouble(tmp << 32);
}
/**
* Calculate the Gaussian for blurring.
*
* @param x
* @param sigma
* @return
*/
static double gaussian(float x, float sigma) {
return exponent(-.5 * (x * x) / (sigma * sigma)) / (sigma * 2.506628);
//return exponent(-.5 * pow(x / sigma, 2)) / (sigma * sqrt(2 * PI));
//return exp(-.5 * pow(x / sigma, 2)) / (sigma * sqrt(2 * PI)); // actual equation
}
/**
* Process the loaded buffer (image).
*
* @param amount
*/
public void operate(int amount) {
ImageRenderContext source = buffer.output;
DataBuffer sourcebuffer = buffer.output.data_buffer;
DataBuffer destbuffer = buffer.buffer.data_buffer;
if (buffer.convolution != 0) {
int W = buffer.output.W;
int H = buffer.output.H;
int Hp = H - h;
// Do X blur
int i = 0;
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
int Y = 0, G = 0;
for (int k = 0; k < s; k++) {
int c = source.get_color_for_convolution.getColor(x + k - h << 8, y << 8);
int w = d[k];
Y += w * (c & 0xff00ff);
G += w * (c & 0x00ff00);
}
temp[i++] = (0xff00ff00 & Y | 0x00ff0000 & G) >> 8;
}
}
// Do Y blur
i = 0;
int notamount = 256 - amount;
for (int y = 0; y < h; y++) {
for (int x = 0; x < W; x++) {
int Y = 0, G = 0;
for (int k = 0; k < s; k++) {
int y2 = (y - h + k + H) % H;
int c = temp[x + W * (y2)];
int w = d[k];
Y += w * (c & 0xff00ff);
G += w * (c & 0x00ff00);
}
int c1 = (0xff00ff00 & Y | 0x00ff0000 & G) >> 8;
int c2 = sourcebuffer.getElem(i) << 1;
int r = ((c2 >> 16) & 0x1fe) - ((c1 >> 16) & 0xff);
int g = ((c2 >> 8) & 0x1fe) - ((c1 >> 8) & 0xff);
int b = ((c2) & 0x1fe) - ((c1) & 0xff);
r = r < 0 ? 0 : r > 0xff ? 0xff : r;
g = g < 0 ? 0 : g > 0xff ? 0xff : g;
b = b < 0 ? 0 : b > 0xff ? 0xff : b;
c2 = (r << 16) | (g << 8) | (b);
c2 = ColorUtility.average(c1, amount, c2, notamount);
destbuffer.setElem(i++, c2);
}
}
for (int y = h; y < Hp; y++) {
for (int x = 0; x < W; x++) {
int Y = 0, G = 0;
for (int k = 0; k < s; k++) {
int c = temp[x + W * (y - h + k)];
int w = d[k];
Y += w * (c & 0xff00ff);
G += w * (c & 0x00ff00);
}
int c1 = (0xff00ff00 & Y | 0x00ff0000 & G) >> 8;
int c2 = sourcebuffer.getElem(i) << 1;
int r = ((c2 >> 16) & 0x1fe) - ((c1 >> 16) & 0xff);
int g = ((c2 >> 8) & 0x1fe) - ((c1 >> 8) & 0xff);
int b = ((c2) & 0x1fe) - ((c1) & 0xff);
r = r < 0 ? 0 : r > 0xff ? 0xff : r;
g = g < 0 ? 0 : g > 0xff ? 0xff : g;
b = b < 0 ? 0 : b > 0xff ? 0xff : b;
c2 = (r << 16) | (g << 8) | (b);
c2 = ColorUtility.average(c1, amount, c2, notamount);
destbuffer.setElem(i++, c2);
}
}
for (int y = Hp; y < H; y++) {
for (int x = 0; x < W; x++) {
int Y = 0, G = 0;
for (int k = 0; k < s; k++) {
int y2 = y - h + k;
if (y2 < 0) {
y2 = 0;
else if (y2 >= H) {
y2 = H - 1;
}
int c = temp[x + W * (y2)];
int w = d[k];
Y += w * (c & 0xff00ff);
G += w * (c & 0x00ff00);
}
int c1 = (0xff00ff00 & Y | 0x00ff0000 & G) >> 8;
int c2 = sourcebuffer.getElem(i) << 1;
int r = ((c2 >> 16) & 0x1fe) - ((c1 >> 16) & 0xff);
int g = ((c2 >> 8) & 0x1fe) - ((c1 >> 8) & 0xff);
int b = ((c2) & 0x1fe) - ((c1) & 0xff);
r = r < 0 ? 0 : r > 0xff ? 0xff : r;
g = g < 0 ? 0 : g > 0xff ? 0xff : g;
b = b < 0 ? 0 : b > 0xff ? 0xff : b;
c2 = (r << 16) | (g << 8) | (b);
c2 = ColorUtility.average(c1, amount, c2, notamount);
destbuffer.setElem(i++, c2);
}
}
} else {
buffer.buffer.data_buffer = buffer.output.data_buffer;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Naming naming naming</strong></p>\n\n<p>Your code is very intimidating - it is filled with single letter variable and members (<code>s,h,e,d</code>...). Those which are not single letter are generic and unhelpful (<code>temp</code>, <code>buffer</code>, <code>notamount</code>...). This makes your code very unreadable.</p>\n\n<p>You also use a lot of literal numbers (<code>2, 256, 1072632447, 60801</code>...) which make no sense to a person who is not familiar with your algorithm. Use constants to make your code more readable.</p>\n\n<p>Your comments are also not useful for someone to read and understand your code.</p>\n\n<p>If you want a serious code review, you must make your code readable, break large methods (<code>operate</code>) into smaller ones, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:00:54.817",
"Id": "72823",
"Score": "0",
"body": "Thanks buddy! I am now the sole developer of Perceptron and I make my own unholy naming convention that I picked up from the days of my unprofessional involvement in C++. This portion of the code originates from the original author's effort made at his college. In one hand, it is recognizable code offered through computer courses. That's what needs evolution. On the other hand, some details are peculiar, because the pixels are stored as integer numbers in a one-dimensional array. Bitwise operators are a speedup. Optimized functions require long explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:13:19.230",
"Id": "72824",
"Score": "0",
"body": "Convolution: of function with function. So, Gauss's function gives the bell-shaped curve return exponent(-.5 * (x * x) / (sigma * sigma)) / (sigma * 2.506628); in the simplified form. The other function is the pixel and its neighborhood. We apply Gauss curve to spread out each pixel to make it fuzzy. Seems detrimental, but in a program where chaos makes visual quality worse, pixel interpolation (rounding of pixels, and a separate issue) and convolution (this issue) are important. Constructor makes a lookup table, and std = 1 is the convolution degree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:14:04.780",
"Id": "72825",
"Score": "0",
"body": "The integer representations of the coordinates are integers multiplied by 256. The format uses 256=1.0, so the actual pixel value is X/256. The extra 8 bits allow the interpolation without using floating point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:22:40.563",
"Id": "72827",
"Score": "0",
"body": "Bitwise operations http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:24:04.160",
"Id": "72829",
"Score": "1",
"body": "@GianniTee, you should refactor your code, so that anyone who reads it, and is unfamiliar with the algorithm, could find his hands and feet... organize your code to bite-sized methods, with meaningful names, and with good use of variable and constant names. You are more than welcome to use bitwise operations, and any other feature of the language - but guide your reader through it. (don't explain what it is, but rather how do _you use it_)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T19:41:28.237",
"Id": "72831",
"Score": "0",
"body": "I am so sorry, I also had the same problem at the beginning and by adding little things, it grew worse, but I was only hoping that someone would recognize the standard, well-known algorithm and then suggest a new one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:11:43.100",
"Id": "73092",
"Score": "0",
"body": "The effect of convolution starts for convolution degree > 1. When its 2, gaussian is 30, 45, 51, 45, which shows how crude the algorithm is and how unimportant the optimized functions are. When 1, gaussian is 0."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T15:01:26.713",
"Id": "42154",
"ParentId": "39592",
"Score": "3"
}
},
{
"body": "<ol>\n<li><p>I think the custom power/exponent methods are a probably waste of time when <code>Math.pow</code> and <code>Math.exp</code> would do just as well in this context.</p></li>\n<li><p>The X/Y passes can be identical except the direction the bell curve is applied in. I'm assuming the extra passes are to handle the edges, but I think you might come out ahead by just doing 2 passes and perform clipping as you go.</p></li>\n<li><p>I think I see some bit-hacking tricks to avoid some divides after going through the inner multiplication loops. I'm not convinced that doing this and going through all the averaging stuff is going to be faster than just doing two simple passes using multiples in the inner loop and 3 integer divides when the loop is complete.</p></li>\n<li><p>Some multiplies can also be eliminated when writing to the temp array by making another array containing the offsets for each row. Like this:</p>\n\n<pre><code>temp = new int[w * h]; \nrow = new int[h];\n\n// make row offsets \nfor(int i = 0; i < h; i++) \n row[i] = w * i; \n\n// write a pixel \ntemp[x + row[y]] = color; \n\n// read a pixel \ncolor = temp[x + row[y]]; \n</code></pre></li>\n<li><p>Try to avoid calling methods within the X loops, they probably have a bigger overhead than you want for this.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-20T23:11:06.280",
"Id": "70475",
"ParentId": "39592",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T13:36:52.383",
"Id": "39592",
"Score": "5",
"Tags": [
"java",
"performance",
"algorithm",
"image",
"bitwise"
],
"Title": "Gaussian blur - convolution algorithm"
}
|
39592
|
<p>I am working on a simple quiz-type game in which the user basically is asked a series of questions and needs to provide an answer.</p>
<p>I'm trying to find a solid/robust way of recording how long it takes for the user to answer each question. This is a web-based game so I am using JavaScript and PHP. I am very inexperienced, so I suspect this is not the best way to do it; at least I hope it's not because it seems very weak. I would appreciate any suggestions as to how to go about making a more full-proof solution. It's not critical that the time be accurate to the millisecond I'm just looking to build something that will be consistent and accurate to within a second or two.</p>
<p>The reason I'm doing it like this rather than just recording the time in the browser is because, as I understand it, the data could theoretically be altered by the user. This is also why I don't send that correct and answers to the browser until the user provides an answer.</p>
<p>Here is my current approach:</p>
<pre><code><?php
/* get_game_data.php
*
* user clicks button to start game
* and triggers ajax request sent to this file
*/
session_start();
if($_SERVER['REQUEST_METHOD'] === 'GET')
{
if(isset($_GET['gamesettings'])){///check certian user defined game options are set
require 'classes/Database.php';
date_default_timezone_set("UTC");
$_SESSION['app_start'] = new DateTime('NOW');////store time at which game/first question starts
$_SESSION['app_index'] = 0;
if($_GET['app'] === 'aural') {
$db = new Database();
$gameData = getGameData($db);///just an example
//etc...
//query database for game data, i.e. the questions,
echo json_encode($gameData['questions]);//then send back to browser
$_SESSION['right_answers'] = $gameData['answers'];///store the right answers to varify against user answers later
}
}
}
?>
<?php
/* post_game_data.php
*
* user answers question in a textbox etc.
* then clicks a submit button which posts the answer to
* this file via ajax again
*/
session_start();
function getTimeTaken($startDTO) {
$endDTO = new DateTime('NOW');
$timeDiff = $startDTO->diff($endDTO);
$timeTaken = $timeDiff->format('%s');
return $timeTaken;
}
date_default_timezone_set("UTC");
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(
isset($_POST['user_answer']) &&
isset($_SESSION['app_index'])
)
{
$index = $_SESSION['app_index'];///current question in the game
$len = count($_SESSION['words']);///number of questions in the game
$userAns = $_POST['user_answer'];
$rightAns = $_SESSION['right_answers'];
if(isset($_SESSION['app_start']))////if this is the first question
{
$responseTime = getTimeTaken($_SESSION['app_start']);
unset($_SESSION['app_start']);
$_SESSION['question_start'] = new DateTime('NOW');
}
else if(isset($_SESSION['question_start']))///not the first question
{
$responseTime = getTimeTaken($_SESSION['question_start']);
$_SESSION['question_start'] = new DateTime('NOW');
}
if($index < $len)
{
$crtAns = $rightAns[$index];
$mark = ($userAns == $crtAns)?1:0;///check user answer against correct answer
$_SESSION['app_index']++;
echo json_encode(array($crtAns, $mark, $responseTime));////send right answer to broswer with mark and response time
}
}
}
?>
</code></pre>
<p>This works pretty much as I would like it to right now but I don't have a live server to test it on, only Apache local host.</p>
|
[] |
[
{
"body": "<p>Matt.</p>\n\n<p>Basically, the idea is correct - start the timer on the server side before the question is send to the user and calculate the duration on the response received. Using <code>DateTime</code> for that is also a great idea, in my opinion.</p>\n\n<p>An alternative solution for you would be storing your gamers response time in the database, but this is a bit more complex. Please feel free to contact me in case you need an advise on that.</p>\n\n<p>The only advise I have for you - try using OOP concepts in your code. All the rest is fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T14:10:47.053",
"Id": "66659",
"Score": "0",
"body": "Thanks, I will eventually be storing the response times in a database. I just wanted to see if using PHP like this was a suitable mechanism for accurately recording the time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T15:51:14.140",
"Id": "39659",
"ParentId": "39593",
"Score": "1"
}
},
{
"body": "<p>Just some simple stuff, \na common.php file for common code used by both files. DRY don't repeat yourself.</p>\n\n<p>Writing a script like you have is fine, the points i have noted will help you if you come back to maintain it in a year or so, and have forgotten how it works. </p>\n\n<p>The bulk of programming jobs are about maintaining a code base, not creating new stuff, so if you can learn how to make maintenance easier, it will be beneficial for you in the long run. (I wish i had learnt this stuff much earlier on)</p>\n\n<p>I have added inline comments explaining the changes i made</p>\n\n<pre><code><?php\n/* common.php */\nrequire 'classes/Database.php';\n\nsession_start();\ndate_default_timezone_set(\"UTC\");\n\n?>\n\n\n\n<?php\n/* get_game_data.php\n *\n * user clicks button to start game\n * and triggers ajax request sent to this file\n */\n\nrequire 'common.php';\n\n// moved into common.php\n// session_start();\n\nif($_SERVER['REQUEST_METHOD'] === 'GET')\n{\n if(isset($_GET['gamesettings'])){///check certian user defined game options are set\n\n // moved into common.php\n// require 'classes/Database.php';\n\n // moved into common.php\n// date_default_timezone_set(\"UTC\");\n\n $_SESSION['app_start'] = new DateTime('NOW');////store time at which game/first question starts\n $_SESSION['app_index'] = 0;\n\n // warning if $_GET['app'] not set this will get a warning notice, we can never trust GET/POST data\n // if($_GET['app'] === 'aural') {\n if(isset($_GET['app']) && $_GET['app'] === 'aural') {\n\n $db = new Database();\n\n $gameData = getGameData($db);///just an example\n //etc...\n //query database for game data, i.e. the questions,\n\n // i prefer to do my internal logic before i output data. this way if something fails i can handle it prior to responding to the user\n $_SESSION['right_answers'] = $gameData['answers'];///store the right answers to varify against user answers later\n\n echo json_encode($gameData['questions']);//then send back to browser\n\n\n\n }\n\n }\n}\n?>\n\n\n\n<?php\n/* post_game_data.php\n *\n * user answers question in a textbox etc.\n * then clicks a submit button which posts the answer to\n * this file via ajax again\n */\n\nrequire 'common.php';\n\n// moved into common.php\n//session_start();\n\n\n\n\n// moved into common.php\n// date_default_timezone_set(\"UTC\");\n\nif($_SERVER['REQUEST_METHOD'] === 'POST')\n{\n // what you have done is not bad, i just prefer to have all user supplied data handled in one place, POST/GET\n // so i know that everything beyond here has been sanitized\n// if(\n// isset($_POST['user_answer']) &&\n// isset($_SESSION['app_index'])\n// )\n\n $userAns = isset($_POST['user_answer']) ? $_POST['user_answer'] : null;\n\n // good variable names can also help reduce the need for comments\n // which of these two following variable names are easier to understand\n\n // $index = $_SESSION['app_index'];///current question in the game\n $current_question_index = isset($_SESSION['app_index']) ? $_SESSION['app_index'] : null;\n\n if($userAns != null && $current_question_index != null)\n {\n\n // same here with variable naming\n // if you are going to maintain these scripts over time, you need to make it easier to remember what is going on\n\n // $len = count($_SESSION['words']);///number of questions in the game\n $num_questions = count($_SESSION['words']);\n\n // handled above, no need to repeat\n // $userAns = $_POST['user_answer'];\n\n $rightAns = $_SESSION['right_answers'];\n\n\n // why use a comment here that could change over time when you can make an easily understandable function name instead\n // if(isset($_SESSION['app_start']))////if this is the first question\n if (is_first_question())\n {\n $responseTime = getTimeTaken($_SESSION['app_start']);\n unset($_SESSION['app_start']);\n\n // $_SESSION['question_start'] = new DateTime('NOW');\n start_question_timer();\n }\n // else if(isset($_SESSION['question_start']))///not the first question \n else if(is_question_started())///not the first question\n {\n $responseTime = getTimeTaken($_SESSION['question_start']);\n\n // $_SESSION['question_start'] = new DateTime('NOW');\n start_question_timer();\n }\n\n // which of these two is going to be easier to understand next year when you come back to maintain your script\n if ($current_question_index < $num_questions) {\n // if($index < $len)\n {\n $crtAns = $rightAns[$current_question_index];\n\n // this is probably overkill in this case, but again why write a comment when you can write a nice function name\n // $mark = ($userAns == $crtAns)?1:0;///check user answer against correct answer\n $mark = mark_user_answer($userAns, $crtAns);\n\n // easy function names to make the code more understandable\n // $_SESSION['app_index']++;\n move_to_next_question();\n\n // given your if {} elseif {} statement above, $responseTime may not have been set, as there is no default case\n // this should be handled properly\n echo json_encode(array($crtAns, $mark, $responseTime));////send right answer to broswer with mark and response time\n }\n\n\n }\n\n}\n\n\n// move functions below main code as what is most important should come first\n// perhaps this function could be called elapsedTimeInSeconds, \n// get infers you are getting a value, and there is no indication what the return type might be\nfunction getTimeTaken($startDTO) {\n\n // good variable naming, easy to understand what is happening\n $endDTO = new DateTime('NOW');\n $timeDiff = $startDTO->diff($endDTO);\n $timeTaken = $timeDiff->format('%s');\n\n return $timeTaken;\n}\n\n\nfunction is_first_question() {\n return isset($_SESSION['app_start']);\n}\n\nfunction is_question_started() {\n return isset($_SESSION['question_start'];\n}\n\n//\nfunction mark_user_answer($user_answer, $correct_answer) {\n return ($user_answer == $correct_answer) ? 1 : 0;\n}\n\nfunction move_to_next_question() {\n $_SESSION['app_index']++;\n}\n\nfunction start_question_timer() {\n $_SESSION['question_start'] = new DateTime('NOW');}\n}\n\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T12:43:56.560",
"Id": "66651",
"Score": "0",
"body": "Thank you for this. I will study this carefully. I posted this mainly just as a proof of concept to see if people thought using sessions like this was a reliable/acceptable way to record user response times. However, there's plenty of great general programming stuff in here that I need to learn too. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T08:38:19.673",
"Id": "39728",
"ParentId": "39593",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39728",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T14:08:10.517",
"Id": "39593",
"Score": "6",
"Tags": [
"php",
"ajax",
"quiz"
],
"Title": "Recording user response times for a quiz"
}
|
39593
|
<p>I wanted to see the site's <em>top sponsors</em> - users that have paid bounties on questions that they didn't own.</p>
<p>I started off with a bounty-related existing query, selected the details into a subquery, and then grouped by sponsor and ended up with <a href="http://data.stackexchange.com/code%20review%20stack%20exchange/query/161056/top-sponsors">this query</a>, which no longer has anything in common with the query I started off with:</p>
<pre><code>select Sponsor,
SponsorRep,
round(sum(cast(BountyClose as float))/(SponsorRep + sum(cast(BountyOpen as float)))*100,2) PctSponsorRep,
count(*) Bounties,
sum(BountyOpen)/count(*) AvgBountyPaid,
sum(BountyOpen) BountyPaid,
sum(BountyClose) BountyAwarded,
avg(cast(DaysOpen as float)) AvgDaysOpen,
max(BountyCloseDate) LastBountyClosed
from (
select
u.DisplayName Sponsor,
u.Reputation SponsorRep,
bo.BountyAmount BountyOpen,
datediff(day, bo.CreationDate, bc.CreationDate) DaysOpen,
bc.BountyAmount BountyClose,
bc.CreationDate BountyCloseDate
from Posts q
inner join Votes bo on q.Id = bo.PostId
and q.PostTypeId = 1 -- Questions
and bo.VoteTypeId = 8 -- BountyOpen
inner join Users op on q.OwnerUserId = op.Id
left join Posts a on a.ParentId = q.Id
and a.PostTypeId = 2 -- Answers
left join Votes bc on a.Id = bc.PostId
and bc.VoteTypeId = 9 -- BountyClose
inner join Users u on bo.UserId = u.Id -- bounty owner
where q.ClosedDate is null
and bc.BountyAmount is not null
and op.Id != u.Id
) subquery
group by Sponsor, SponsorRep
order by
sum(BountyClose) desc,
max(BountyCloseDate) desc
</code></pre>
<p>Is there anything else I could have done better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T22:59:20.520",
"Id": "66441",
"Score": "0",
"body": "Returns 10 rows in < 1 ms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:26:29.347",
"Id": "66448",
"Score": "3",
"body": "10 rows returned in 1 ms **(cached)** :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T01:00:07.917",
"Id": "66465",
"Score": "0",
"body": "@DavidHarkness good catch. It's more like 55 ms, with 41% x2 (82%) being spent doing a **Clustered Index Scan** on [Votes].[UIX_Votes_Id]. Does it get any better?"
}
] |
[
{
"body": "<p>I would change some things.</p>\n\n<p>This:</p>\n\n<pre><code>inner join Votes bo on q.Id = bo.PostId \n and q.PostTypeId = 1 -- Questions\n and bo.VoteTypeId = 8 -- BountyOpen\n</code></pre>\n\n<p>kind of stuff needs to go in the where statement. The join on the ID's is ok\nbecause that is how the table relates, but the other two and situations are for filtering the results. That should be in the where statement.</p>\n\n<hr>\n\n<p>Inside the where statement you have</p>\n\n<pre><code>AND op.ID <> u.Id \n</code></pre>\n\n<p>that should be in a join, more specifically a <code>FULL OUTER JOIN</code> or maybe better a <code>LEFT OUTER JOIN</code> (<code>LEFT JOIN</code>) .</p>\n\n<p><strong>NOTE</strong></p>\n\n<p>The reason that I say this last one is because I have sort of done a little bit of research.</p>\n\n<p>I have seen several questions where they had a <code><></code> in the where clause, and they were asking about performance. </p>\n\n<p>Turns out that the way that SQL works a <code><></code> or a <code>NOT IN</code> clause in the where statement slows down the query, and it is better to try and <code>OUTER JOIN</code> or <code>LEFT JOIN</code> on that column where possible. </p>\n\n<p>I mention this more in <a href=\"https://codereview.stackexchange.com/a/35232/18427\">my answer</a>.</p>\n\n<p>In the answer I mention a Stack Overflow answer to <a href=\"https://stackoverflow.com/a/7419299/1214743\">this question</a>.</p>\n\n<p>This may or may not be usable in your query, but it is something nice to know.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:51:17.690",
"Id": "66454",
"Score": "0",
"body": "I wonder, readability-wise, if it's best to filter `q` and `a` in the `WHERE` clause. `q` is `Posts`, so is `a`; then being filtered as soon as they're encountered makes it clear that `q` only contains questions and that `a` only contains answers. I'd like to read more about ON-clause filtering; is it ever appropriate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:18:06.460",
"Id": "66460",
"Score": "0",
"body": "I don't know if it is appropriate or not. it doesn't look right to me. I would do it both ways and see what the performance difference is. you should see if you can do an Explain on the SEDE"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T01:05:30.720",
"Id": "66466",
"Score": "0",
"body": "The two query plans are apparently identical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T01:07:09.800",
"Id": "66467",
"Score": "1",
"body": "If it makes any difference, MySQL simply moves everything in the joins to the `where` clause."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T04:39:16.790",
"Id": "66486",
"Score": "1",
"body": "For the record, not that it matters in this query… conditions in the `WHERE` clause are not exactly the same as conditions in the `JOIN ON` clause. You can use a `JOIN ON` condition to cause it to join `NULL` to `NULL`, for example; that's not possible in the `WHERE` clause."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:25:50.580",
"Id": "66491",
"Score": "0",
"body": "@200_success Besides those statements are clearly `WHERE` statements disguised as join on statements"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T16:53:00.840",
"Id": "66675",
"Score": "1",
"body": "@200_success, I just looked at this comment stream again, you are right that the two conditions are different, that is what I was saying, OP has conditions that are visibly where conditions and not `ON` conditions."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T22:53:21.010",
"Id": "39614",
"ParentId": "39602",
"Score": "5"
}
},
{
"body": "<p>You don't need the <code>op</code> join on <code>Users</code> since you can compare the user IDs in the question directly. Remove that join and in the where clause replace</p>\n\n<pre><code>and op.Id != u.Id\n</code></pre>\n\n<p>with</p>\n\n<pre><code>and q.OwnerUserId != bo.UserId\n</code></pre>\n\n<p>or move this to the first join on <code>Votes</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:20:17.823",
"Id": "39618",
"ParentId": "39602",
"Score": "7"
}
},
{
"body": "<p>I have looked at this query/report, and from the beginning I figured it must be missing something. I looked through the SQL, and can't identify it off-hand, so I figured I would build my own query, and see how they compare. The results I got are very different... :(</p>\n\n<hr>\n\n<p><strong>Edit: Found the problem</strong></p>\n\n<p>You cannot chain two outer joins.... Consider the query for the missing <code>Quentin</code> votes:</p>\n\n<p>We know from the alternate query, and from Quentin's profile, that <a href=\"https://codereview.stackexchange.com/users/11227/quentin-pradet?tab=bounties&sort=offered\">he offered a 150 bounty</a>. This 150 does not show up on your query.</p>\n\n<p>Here is a base query <a href=\"http://data.stackexchange.com/codereview/revision/161395/205718/huntingbugsinbountyjoins\" rel=\"nofollow noreferrer\">that matches your query and it should show this bounty</a>.</p>\n\n<p>it does not. But, if we convert the final outer-joins on alias <code>a</code> and alias <code>bc</code> to an equi-join, and make it a <code>with</code> statement, <a href=\"http://data.stackexchange.com/codereview/query/161395/huntingbugsinbountyjoins\" rel=\"nofollow noreferrer\">it all of a sudden works</a>....</p>\n\n<p>The reason is because we need the two outer joins, and the <strong>first</strong> one succeeds. The first one gets answers to the question (there may not be answers, so we need the outer join). The second outer-join looks for bounty-votes, and the bounty may not be awarded.</p>\n\n<p>I am not sure why this is not working, could be a SQLServer bug?</p>\n\n<p><strong>Second update</strong> This issue also accounts for the missing 2 bounties from 200_success... because they are on questions which have answers, but the answers were not awarded the bounty.</p>\n\n<p>This <em>also</em> explains why some offered-but-not-awarded bounties are working, because they were on questions with <strong>no answers</strong>.</p>\n\n<hr>\n\n<p><strong>Alternate query here</strong></p>\n\n<p>I have put together this report <a href=\"http://data.stackexchange.com/codereview/query/161292/bountifulii\" rel=\"nofollow noreferrer\">BountifulII</a>. Obviously, there could be problems with my report too (offer it as a question? - Week-end challenge?).</p>\n\n<p>Note that my report has a couple of odd <code>--firewall fix</code> comments in it, see <a href=\"https://meta.stackexchange.com/questions/216823/bizarre-problem-on-chat-and-sede-with-group-by\">this MSO Question</a> for the reason... ;-)</p>\n\n<p>My report does a more general process of calculating who offered bounties, and who was awarded bounties. It separates out awarded-bounties to those awarded to their own questions, and those awarded to any question). In the final report it lists the <code>Promotions</code> and <code>PromotedAmount</code>. These values should match with the values in your reports.... but they do not.</p>\n\n<p>here is the revised SQL:</p>\n\n<pre><code>WITH Bounties AS (\n SELECT\n UserID AS UserID,\n 0 AS GetCount,\n 0 AS GetAmount,\n COUNT(BountyAmount) AS GiveCount,\n SUM(BountyAmount) AS GiveAmount,\n SUM(case when Posts.OwnerUserId = Votes.UserId then 1 else 0 end) AS SelfCount,\n SUM(case when Posts.OwnerUserId = Votes.UserId then BountyAmount else 0 end) AS SelfAmount\n FROM Votes,\n Posts\n WHERE Votes.PostId = Posts.Id\n AND VoteTypeId = 8\n GROUP --firewall fix\n BY UserID\n UNION\n SELECT\n Posts.OwnerUserID AS UserID,\n COUNT(BountyAmount) AS GetCount,\n SUM(BountyAmount) AS GetAmount,\n 0 AS GiveCount,\n 0 AS GiveAmount,\n 0 AS SelfCount,\n 0 AS SelfAmount\n FROM Votes,\n Posts\n WHERE Votes.PostId = Posts.ID\n AND VoteTypeId = 9\n GROUP --firewall fix\n BY Posts.OwnerUserID\n ) \n\nSELECT UserID AS [User Link],\n SUM(GiveCount - SelfCount) AS Pomotions,\n SUM(GiveAmount - SelfAmount) AS PromotedAmount,\n SUM(GetCount) AS GetCount,\n SUM(GetAmount) AS GetAmount,\n SUM(GiveCount) AS GiveCount,\n SUM(GiveAmount) AS GiveAmount,\n SUM(SelfCount) AS SelfCount,\n SUM(SelfAmount) AS SelfAmount,\n SUM(GiveCount + GetCount) AS EventCount,\n SUM(GetAmount - GiveAmount) AS NetBenefit\nFROM Bounties\nGROUP -- firewall fix\nBY UserID\nORDER BY PromotedAmount DESC, EventCount DESC, NetBenefit DESC\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T18:19:15.017",
"Id": "39670",
"ParentId": "39602",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "39670",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:10:37.550",
"Id": "39602",
"Score": "13",
"Tags": [
"sql",
"sql-server",
"t-sql",
"stackexchange"
],
"Title": "SEDE Top Sponsors"
}
|
39602
|
<p>I'm trying to implement a left leaning red black tree as described <a href="http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf" rel="nofollow">here</a>. This is their snippet for insert</p>
<pre><code>private Node insert(Node h, Key key, Value value) {
if (h == null) return new Node(key, value);
if (isRed(h.left) && isRed(h.right)) colorFlip(h);
int cmp = key.compareTo(h.key);
if (cmp == 0) h.val = value;
else if (cmp < 0) h.left = insert(h.left, key, value);
else h.right = insert(h.right, key, value);
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
return h;
}
</code></pre>
<p>My attempt at a port in Haskell is... quite ugly, with a lot of repetition. I think it's because I'm still thinking procedurally. Any feedback on what I should do differently? Or is there no way around having many next-state variables (<code>x', x'', x'''</code>)? Should I be approaching this completely differently?</p>
<pre><code>data Colour = Red | Black deriving (Show)
data Tree a
= Branch (Tree a) a (Tree a) Colour
| Leaf
deriving (Show)
add :: (Ord a) => Tree a -> a -> Tree a
add tree val
= let
(Branch left' node' right' _) = fix_up $ do_add tree val
in (Branch left' node' right' Black) -- root always black
do_add :: (Ord a) => Tree a -> a -> Tree a
do_add (Branch left node right colour) val
| val < node = (Branch (add left val) node right colour)
| val > node = (Branch left node (add right val) colour)
| otherwise = (Branch left node right colour)
do_add Leaf val = (Branch Leaf val Leaf Black)
get_left_node :: Tree a -> Tree a
get_left_node (Branch left _ _ _) = left
get_left_node Leaf = Leaf
fix_up :: Tree a -> Tree a
fix_up (Branch left node right colour)
= let
branch' = if ((not (is_red left)) && (is_red right)) then (rotate_left (Branch left node right colour)) else (Branch left node right colour)
(Branch left' _ right' _) = branch'
branch'' = if ((is_red left') && (is_red (get_left_node left'))) then (rotate_right branch') else branch'
(Branch left'' _ right'' _) = branch''
branch''' = if ((is_red left'') && (is_red right'')) then (flip_colours branch'') else branch''
in branch'''
rotate_left :: Tree a -> Tree a
rotate_left (Branch left node (Branch right_left right_node right_right right_colour) colour)
= let
left' = (Branch left node right_left Red)
centre' = (Branch left' right_node right_right colour)
in centre'
rotate_right :: Tree a -> Tree a
rotate_right (Branch (Branch left_left left_node left_right left_colour) node right colour)
= let
right' = (Branch left_right node right Red)
centre' = (Branch left_left left_node right' colour)
in centre'
flip_colours :: Tree a -> Tree a
flip_colours (Branch (Branch left_left left_node left_right left_colour) node (Branch right_left right_node right_right right_colour) colour) = let
left' = (Branch left_left left_node left_right (invert_colour left_colour))
right' = (Branch right_left right_node right_right (invert_colour right_colour))
centre' = (Branch left' node right' (invert_colour colour))
in centre'
is_red :: Tree a -> Bool
is_red (Branch _ _ _ Red) = True
is_red _ = False
is_black :: Tree a -> Bool
is_black node = not $ is_red node
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T19:53:49.560",
"Id": "66825",
"Score": "1",
"body": "Could you please make the code snippet [self-contained](http://sscce.org/), add the data type definition etc., so that it can be readily compiled? It'd help analyzing and perhaps refactoring it a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T21:27:08.693",
"Id": "66987",
"Score": "0",
"body": "@PetrPudlák sorry for the late reply. I added all the code. (I haven't tested it extensively but it seems to work for basic examples at in ghci). I refactored it a bit (decided it was better to have separate helper functions, instead of local lambda helpers), but you can see in `fix_up` it's very much procedural"
}
] |
[
{
"body": "<p>The code looks much better after refactoring!</p>\n\n<p>Additionally I'd strongly suggest to keep line lengths within some limit. Usual choices are something between 72 and 80. There are two reasons for it:</p>\n\n<ul>\n<li>People with smaller screens aren't able to see a piece code at once and have to scroll. This makes reading the code next to impossible (like when your snippet here on SO doesn't fit into its frame).</li>\n<li>Even for a person with a wide screen it's difficult to read text with long lines. It's <a href=\"http://baymard.com/blog/line-length-readability\" rel=\"nofollow noreferrer\">hard for eyes</a> to focus where the next line starts.</li>\n</ul>\n\n<p>Don't be afraid to use short identifiers, if theirs scope is limited to a short function. For example, in my opinion this</p>\n\n<pre><code>rotate_left :: Tree a -> Tree a\nrotate_left (Branch l v (Branch rl rv rr _rc) c)\n = (Branch (Branch l v rl Red) rv rr c)\n</code></pre>\n\n<p>is more readable, and it's visually easy to spot what is going on.</p>\n\n<p>One thing that will also help you make the code shorter more readable is using <a href=\"http://www.haskell.org/tutorial/patterns.html\" rel=\"nofollow noreferrer\">as-patterns</a> (see also <a href=\"https://stackoverflow.com/q/1153465/1333025\">this question</a>):</p>\n\n<pre><code>do_add :: (Ord a) => Tree a -> a -> Tree a\ndo_add branch@(Branch left node right colour) val\n | val < node = (Branch (add left val) node right colour)\n | val > node = (Branch left node (add right val) colour)\n | otherwise = branch -- HERE: we don't need to recreate the node\ndo_add Leaf val = (Branch Leaf val Leaf Black)\n</code></pre>\n\n<p>It also can give a small performance boost as we don't re-create objects identical to those we pattern match on.</p>\n\n<p>Concerning <code>fix_up</code>: Let's try to factor out common and duplicate code. The common pattern is that we check some conditions on the sub-nodes of a node and if it's true, we apply a function or it. Otherwise we keep it intact. We can split this idea into two functions - one that is general, and other that is then specialized for branches:</p>\n\n<pre><code>fix_up :: Tree a -> Tree a\nfix_up =\n onBr [is_red] [is_red] flip_colours .\n onBr [is_red, is_red . get_left_node] [] rotate_right .\n onBr [not . is_red] [is_red] rotate_left\n where\n -- Apply a function on a branch, if its left and right subnodes match\n -- given predicates.\n onBr :: [Tree a -> Bool] -> [Tree a -> Bool]\n -> (Tree a -> Tree a) -> (Tree a -> Tree a)\n onBr lps rps = on (\\b -> all ($ get_left_node b) lps\n && all ($ get_right_node b) rps)\n -- Apply a function on a value, if it matches a predicate.\n on :: (a -> Bool) -> (a -> a) -> (a -> a)\n on p f x | p x = f x\n | otherwise = x\n</code></pre>\n\n<p>This allows us to represent the whole operation as the composition of several functions. And it localizes bindings of subnodes (<code>l</code> and <code>r</code>) to the predicates, which again helps readability.</p>\n\n<hr>\n\n<p>I'd also like to draw your attention to <a href=\"https://en.wikipedia.org/wiki/AA_tree\" rel=\"nofollow noreferrer\">AA trees</a>. They have very similar performance as red-black trees, but are simpler and easier to implement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T00:16:39.980",
"Id": "67439",
"Score": "0",
"body": "Thanks for all the recommendations! I remember reading about short variable names in functional languages from Scala but never made the connection to do it here. I was also looking for the `as` pattern (which you can do with the bind operator in Erlang) but didn't know what it was called. The predicates are cool too. Finally thanks for pointing me to AA trees!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T22:20:27.790",
"Id": "67594",
"Score": "0",
"body": "PS: I just understood your use of the `$`... wow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T22:26:04.297",
"Id": "67596",
"Score": "0",
"body": "@Raekye I forgot to explain it. `($ x)` is a function that takes another function and applies it on `x`. It's a partial application of `($)`, supplying its second argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T22:33:17.110",
"Id": "67600",
"Score": "0",
"body": "Haha yeah no worries I enjoyed figuring it out myself; really felt like a divine revelation :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T22:35:26.277",
"Id": "67601",
"Score": "0",
"body": "@Raekye Interestingly, `($)` is just a specialization of `id`. It'd be possible to also write (`id` x), although that'd be quite uncommon and less readable."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T08:00:27.053",
"Id": "39943",
"ParentId": "39607",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39943",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T20:55:30.817",
"Id": "39607",
"Score": "10",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "(How) should I avoid writing procedural code in Haskell?"
}
|
39607
|
<p><sup>Please note that all credit for code goes to humanoid24 and I have only helped the bare minimum required to be able to post it here.</sup></p>
<p>I am working with some friends to replicate a server for the game LEGO® Universe which was shut down two years ago. This code is included in the LUNIServer v3 <a href="http://bit.ly/lu-d" rel="nofollow">here</a>.</p>
<p>The server does what it's supposed to do, but I'm wondering if anything could be improved. If you have any tips to make this more efficient (not necessarily smaller), please post them. I'll need to change stuff before the server grows larger, making a major change hard to do.</p>
<pre><code>/*
Lego Universe Authentification Server WIP
Code done by humanoid24 (aka Triver) as of 01.12.2013
This source code requires RakNet version 3.25 as
an external dependency to work with the luni client.
*/
//#define USE_ENCRYPTION // is actually not required for a connection (but may be useful once login works because of user password)
#include "serverLoop.h"
#include <fstream>
//#if defined USE_ENCRYPTION
#include "RSACrypt.h"
//#endif
void loadConfig(CONNECT_INFO* cfg) // do a very simple and dirty config loading
{
memset(cfg->redirectIp, 0, sizeof(cfg->redirectIp));
std::ifstream in(".\\config.ini", std::ios::in);
if(in.is_open())
{
std::string temp((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
in.close();
size_t pos = temp.find("redirect_ip=", 0)+strlen("redirect_ip=");
size_t end = temp.find_first_of('\n', pos);
if(end > pos)
{
std::string value = temp.substr(pos, end-pos);
if(value.size() < sizeof(cfg->redirectIp))
memcpy(cfg->redirectIp, value.c_str(), value.size());
else
printf("specified host exceeds limit of 15!\n");
pos = temp.find("redirect_port=", end)+strlen("redirect_port=");
end = temp.find_first_of('\n', pos);
if(end > pos)
{
cfg->redirectPort = atoi(temp.substr(pos, end-pos).c_str());
pos = temp.find("listen_port=", end)+strlen("listen_port=");
end = temp.find_first_of('\n', pos);
if(end > pos)
{
cfg->listenPort = atoi(temp.substr(pos, end-pos).c_str());
pos = temp.find("use_encryption=", end)+strlen("use_encryption=");
end = temp.find_first_of('\n', pos);
if(end > pos)
{
std::string value = temp.substr(pos, end-pos);
if(value.compare("true") == 0 || value.compare("1") == 0)
cfg->useEncryption = true;
else
cfg->useEncryption = false;
pos = temp.find("log_file=", end)+strlen("log_file=");
end = temp.find_first_of('\n', pos);
if(end == std::string::npos)
end = temp.size();
if(end > pos)
{
value = temp.substr(pos, end-pos);
if(value.compare("true") == 0 || value.compare("1") == 0)
cfg->logFile = true;
else
cfg->logFile = false;
}
}
}
}
}
}
else
{
printf("Couldn't open config.ini, check if file exists and if you have permission\n");
cfg->redirectPort = -1;
cfg->listenPort = 1001; // just set auth port as default
cfg->logFile = true;
cfg->useEncryption = false;
}
}
void InitSecurity(RakPeerInterface *rakServer, bool useEncryption)
{
// luni client requires this password, seems to be the same for all versions (even alpha/beta)
rakServer->SetIncomingPassword("3.25 ND1", 8);
if(useEncryption)
{
// These are the sizes necessary for e,n,p,q
big::u32 e; RSA_BIT_SIZE n; // e,n is the public key
BIGHALFSIZE(RSA_BIT_SIZE, p); BIGHALFSIZE(RSA_BIT_SIZE, q); // p,q is the private key
bool keyLoaded = false;
FILE* fp = fopen("public_key.bin", "rb");
if(fp)
{
printf("Loading public key... ");
fread((char*)(&e), sizeof(e), 1, fp);
fread((char*)(n), sizeof(n), 1, fp);
fclose(fp);
}
else
printf("Failed to open \"public_key.bin\".\n");
fp = fopen("private_key.bin", "rb");
if(fp)
{
printf("Loading private key... ");
fread(p, sizeof(RSA_BIT_SIZE)/2, 1, fp);
fread(q, sizeof(RSA_BIT_SIZE)/2, 1, fp);
fclose(fp);
printf("Done.\n");
keyLoaded=true;
}
else
printf("Failed to open \"private_key.bin\".\n");
big::RSACrypt<RSA_BIT_SIZE> rsacrypt;
if(!keyLoaded) // if there's no predefined key just generate one (and write them on disk)
{
printf("Generating %i byte key.\n", sizeof(RSA_BIT_SIZE));
rsacrypt.generateKeys();
rsacrypt.getPublicKey(e,n);
rsacrypt.getPrivateKey(p,q);
printf("Keys generated.\n");
printf("Writing public key... ");
FILE* fp = fopen("public_key.bin", "wb");
fwrite((char*)&e, sizeof(e), 1, fp);
fwrite((char*)n, sizeof(n), 1, fp);
fclose(fp);
printf("Writing private key... ");
fp = fopen("private_key.bin", "wb");
fwrite(p, sizeof(RSA_BIT_SIZE)/2, 1, fp);
fwrite(q, sizeof(RSA_BIT_SIZE)/2, 1, fp);
fclose(fp);
printf("Done.\n");
}
else
rsacrypt.setPrivateKey(p, q);
//rakServer->InitializeSecurity(0,0,0,0); // directly generate the keys
rakServer->InitializeSecurity(0, 0, (char*)p, (char*)q); // e and n are actually not required
}
}
int main(void)
{
RakPeerInterface *rakServer = RakNetworkFactory::GetRakPeerInterface();
CONNECT_INFO cfg;
loadConfig(&cfg);
PacketLogger msgConsoleHandler;
PacketFileLogger msgFileHandler;
rakServer->AttachPlugin(&msgConsoleHandler);
if(cfg.logFile)
rakServer->AttachPlugin(&msgFileHandler);
printf("Initializing luni test server\n");
InitSecurity(rakServer, cfg.useEncryption);
SocketDescriptor socketDescriptor(cfg.listenPort, 0); // port 1001 == luni auth, ports 2001-2200 == char or world
bool success = rakServer->Startup(8, 30, &socketDescriptor, 1);
rakServer->SetMaximumIncomingConnections(8);
if(success)
{
printf("Successfully initialized, listening for packets on port %i...\n\n", cfg.listenPort);
printf("RakNet log format:\n");
msgConsoleHandler.LogHeader();
if(cfg.logFile)
{
msgFileHandler.StartLog(0);
listenForPackets(rakServer, &msgFileHandler, &cfg);
}
else
listenForPackets(rakServer, NULL, &cfg);
}
else
{
char* quitMsg = "Failed to initialize the server, exiting...\n";
msgFileHandler.WriteLog(quitMsg);
printf(quitMsg);
}
rakServer->Shutdown(0);
RakNetworkFactory::DestroyRakPeerInterface(rakServer);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:36:59.610",
"Id": "66432",
"Score": "0",
"body": "This question appears to be off-topic because it is about reviewing code that the OP has not written. Please see our [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:42:30.737",
"Id": "66433",
"Score": "0",
"body": "Fixed (I'm helping with it too)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:46:21.320",
"Id": "66434",
"Score": "0",
"body": "Close vote retracted :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T16:40:13.127",
"Id": "66528",
"Score": "2",
"body": "I would name it differently, LEGO is trademarked after all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T17:06:59.340",
"Id": "66535",
"Score": "0",
"body": "@tomdemuyt Fixed."
}
] |
[
{
"body": "<p>I've only skimmed a little bit of your code, but here's what I found so far:</p>\n\n<p>Always make sure <code>std::string</code> methods do not return <code>std::string::npos</code>.</p>\n\n<pre><code>size_t pos = temp.find(\"redirect_ip=\", 0)+strlen(\"redirect_ip=\");\n</code></pre>\n\n<p>This can easily lead to undefined behavior. <code>size_t</code> is an unsigned integral type. On some systems, <code>std::string::npos</code> is defined as 0xffffffff. You are guaranteed an overflow if this is the case on your system and your call to <code>find</code> fails. </p>\n\n<p><br/> </p>\n\n<pre><code> size_t end = temp.find_first_of('\\n', pos);\n if(end > pos)\n {\n std::string value = temp.substr(pos, end-pos);\n</code></pre>\n\n<p>If <code>end == std::string::npos</code>, then you're going to be reading way out of bounds. </p>\n\n<p><br/></p>\n\n<pre><code>if(value.compare(\"true\") == 0 || value.compare(\"1\") == 0)\n</code></pre>\n\n<p>There is no reason to use <code>compare</code> here. An <code>std::string</code>'s <code>operator==</code> is overloaded to check for equality. This would be better: </p>\n\n<pre><code>if(value == \"true\" || value == \"1\")\n</code></pre>\n\n<p><br/><br>\nYour entire structure of nested <code>if</code> statements is ugly to me. I would rather use exceptions instead or return early.</p>\n\n<p>Be consistent with your API. In <code>loadConfig</code>, you use C++-style streams, but in <code>InitSecurity</code>, you use C-style file descriptors. Unless you've profiled your code and decided C++-style streams are too slow, I would stick to those. If you have profiled your code and decided that C-style descriptors give you an adequate boost, then you should document that detail in a comment. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T19:32:23.563",
"Id": "39673",
"ParentId": "39608",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:07:16.167",
"Id": "39608",
"Score": "5",
"Tags": [
"c++",
"optimization",
"server",
"authentication",
"raknet"
],
"Title": "LEGO® Universe Authentication Server"
}
|
39608
|
<p>I am just starting to program in C#, so I am a beginner. I've been practicing some coding and I would like your opinion on something. </p>
<p>I have a flying direction for a plane, e.g. ''London - Berlin'' (direction). I want to create a method that will return the first and the last consonant of the plane's starting point (London), and the first and the last consonant of the plane's destination (Berlin).</p>
<p>I have written this, so I would like to know if it's ok, or if you have some suggestions:</p>
<pre><code>public class Flight
{
private string direction;
public Flight(string direction)
{
this.direction = direction;
}
public string Consonants()
{
string starting = direction.Split('-')[0];
string destination = direction.Split('-')[1];
string startConsonants = starting.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");
string destConsonants = destination.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");
return string.Format("{0}{1}-{2}{3}", startConsonants[0].ToString(), startConsonants[startConsonants.Length-1].ToString(), destConsonants[0].ToString(), destConsonants[destConsonants.Length-1].ToString());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:46:23.990",
"Id": "66480",
"Score": "1",
"body": "Your code doesn't appear to address surrounding the `-` with spaces like in your example. Is this a bug, or did you just make a mistake when you wrote the example value?"
}
] |
[
{
"body": "<p>Your code is working but repeating all those <code>Replace</code> seems to be unnecessary. Firstly, you repeat them five times for single word and then once again two times because of processing two words. Code becomes long and unclear. Always, when we repeat code, it is good time to think about improvements and reducing those repeats.</p>\n\n<p>So first, I would start to think about reducing repeats in line:</p>\n\n<pre><code>string startConsonants = starting.ToUpper().Replace(\"A\", \"\").Replace(\"E\", \"\").Replace(\"I\", \"\").Replace(\"O\", \"\").Replace(\"U\", \"\");\n</code></pre>\n\n<p>You can do, for example, use LINQ:</p>\n\n<pre><code>string vowels = \"aeiou\";\nvar consonants = starting.Where(c => !vowels.Contains(char.ToLowerInvariant(c))); // (1)\n</code></pre>\n\n<p>And then simply, instead of operating on arrays <code>startConsonants[0].ToString()</code> and <code>startConsonants[startConsonants.Length-1].ToString()</code>, you can write:</p>\n\n<pre><code>char first = consonants.First();\nchar last = consonants.Last();\n</code></pre>\n\n<p>This code is more clear than yours because it has clear intention: select only not vowels and then take first and last of them. No repeating code, no indices calculation etc.</p>\n\n<p>Then, to not repeat line (1) two times, I would create a method for it:</p>\n\n<pre><code>public string GetConsonants(string input)\n{\n string vowels = \"aeiou\";\n var consonats = input.Where(c => !vowels.Contains(char.ToLowerInvariant(c)));\n return new string(consonats.ToArray());\n}\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>public string Consonants()\n{\n string starting = direction.Split('-')[0];\n string destination = direction.Split('-')[1];\n\n string startConsonants = GetConsonants(starting);\n string destConsonants = GetConsonants(destination);\n\n return string.Format(\"{0}{1}-{2}{3}\", startConsonants.First(), startConsonants.Last(), destConsonants.First(), destConsonants.Last());\n}\n</code></pre>\n\n<p>Eventually, to go along with .NET/C# ideology, I would create an extension methods for <code>Char</code> and <code>String</code> to make everything clear:</p>\n\n<pre><code>public static class CharExtensions\n{\n private static string Vowels = \"aeiou\";\n\n public static bool IsVowel(this Char chr)\n {\n return Vowels.Contains(char.ToLowerInvariant(chr));\n }\n\n public static bool IsConsonant(this Char chr)\n {\n return !IsVowel(chr);\n }\n}\n\npublic static class StringExtensions\n{\n public static string OnlyConsonants(this String str)\n {\n return new string(str.Where(c => c.IsConsonant()).ToArray());\n }\n}\n</code></pre>\n\n<p>and then: </p>\n\n<pre><code>public string Consonants()\n{\n string starting = direction.Split('-')[0];\n string destination = direction.Split('-')[1];\n\n string startConsonants = starting.OnlyConsonants();\n string destConsonants = destination.OnlyConsonants();\n\n return string.Format(\"{0}{1}-{2}{3}\", startConsonants.First(), startConsonants.Last(), destConsonants.First(), destConsonants.Last());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:07:26.483",
"Id": "66443",
"Score": "0",
"body": "Two small comments: upper-case 'A' is a vowel too; and LINQ is a lot (may be too much) for an OP who \"is just starting to program in C#\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:48:32.957",
"Id": "66452",
"Score": "0",
"body": "@ChrisW, thanks for pointing out `A` issue. But with LINQ, I do not agree. The sooner beginner will be aware of such a core C# feature as LINQ, the sooner it will not produce a tons of not ever needed loops and functions just to reinvent the wheel. But of course, if someone is starting to program in general, it is better to reinvent the wheel just to teach how it works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:30:31.327",
"Id": "66462",
"Score": "0",
"body": "This is actually good; too much or not, it's never too early to at least hear about new ways to do something. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:13:16.060",
"Id": "66487",
"Score": "0",
"body": "@KonradKokosa I agree about LINQ, for one, it is one of the major reasons to use C# vs. other languages. Also, it can reduce what would be a tedious, clumsy half dozen lines in other languages to a single self explanatory line with obvious intent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:16:33.150",
"Id": "66488",
"Score": "0",
"body": "Also, this answer invokes the assumption: \"Anything that isn't a vowel must be a consonant.\" This is obviously untrue. For instance, cities may have symbols like apostrophes or dashes, the method of defining vowels is also prone to pitfalls like `ø` or `ä`. (Though then again, consonants are also subject to this issue.)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T22:38:22.997",
"Id": "39613",
"ParentId": "39611",
"Score": "10"
}
},
{
"body": "<p>Perhaps I'm over-thinking this but ...</p>\n\n<blockquote>\n <p>I want to create a method that will return the first and the last consonant of the plane's starting point (London)</p>\n</blockquote>\n\n<ul>\n<li>What should be returned if the plane's starting point is one of the places listed in <a href=\"http://en.wikipedia.org/wiki/List_of_short_place_names\">List of short place names</a>, for example <code>A</code> or <code>Hồ</code> or <code>Yu</code>?</li>\n<li>What if the place name is somewhere like <code>東京</code>?</li>\n<li>Is the letter <code>y</code> a consonant or a vowel?</li>\n</ul>\n\n<p>Part of programming is to be clear about the 'functional specification' or 'requirements' for the program, and to think about 'edge cases' or 'exceptions' (like, what if the network is down, what if the bank account is empty, what if the user is already signed in or signed out, etc.).</p>\n\n<p>As for your code ...</p>\n\n<hr>\n\n<p>This is OK ...</p>\n\n<pre><code> string starting = direction.Split('-')[0];\n string destination = direction.Split('-')[1];\n</code></pre>\n\n<p>... but it's my habit to avoid making more API calls than I must. So I might call it as:</p>\n\n<pre><code>string[] split = direction.Split('-');\nDebug.Assert(split.Length == 2);\nstring starting = split[0];\nstring destination = split[1];\n</code></pre>\n\n<hr>\n\n<p>This is expensive ...</p>\n\n<pre><code>starting.ToUpper().Replace(\"A\", \"\").Replace(\"E\", \"\").Replace(\"I\", \"\").Replace(\"O\", \"\").Replace(\"U\", \"\");\n</code></pre>\n\n<p>... because there are many string operations: each Replace creates a new string. It may return the wrong answer too: the ToUpper() means that you return 'N' instead of 'n' as the last consonant in \"London\".</p>\n\n<hr>\n\n<p>This is obviously just a 'test' or 'example' class ...</p>\n\n<pre><code>public class Flight\n{\n private string direction;\n\n public Flight(string direction)\n {\n this.direction = direction;\n }\n\n public string Consonants()\n {\n string starting = direction.Split('-')[0];\n\n ... etc ...\n }\n}\n</code></pre>\n\n<p>... so I can't comment on whether this is good \"object-oriented design\". Another way to present this code would be as a 'static' or more stand-alone (doesn't depend on instance data) method, for example like this:</p>\n\n<pre><code>public static class Flight\n{\n // Expects input string format like \"London - Berlin\", returns \"LN-BN\"\n public static string GetConsonants(string direction)\n {\n string starting = direction.Split('-')[0];\n\n ... etc ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:28:39.520",
"Id": "66461",
"Score": "0",
"body": "Sorry, my bad, I was not thinking about it. For now, let's assume there are not symbols such as 東京. Also, in my native language we know by default that there are exactly 5 vowels (aeiou), and that's why I didn't consider y. Sorry again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:33:32.737",
"Id": "66463",
"Score": "1",
"body": "In English, the 'y' in \"Derry\" would be considered a vowel, but the 'y' in \"York\" would be a consonant: http://www.oxforddictionaries.com/words/is-the-letter-y-a-vowel-or-a-consonant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:19:50.130",
"Id": "66489",
"Score": "0",
"body": "+1 for `y` - very subtle bug which is likely to cause issues and quite difficult to solve. Another example: Ypres, in Belgium."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T22:54:39.197",
"Id": "39615",
"ParentId": "39611",
"Score": "10"
}
},
{
"body": "<p>I think there is room for improvement in the following areas:</p>\n\n<ol>\n<li>Duplication of logic and data (this harms maintainability and readability)</li>\n<li>Mixing of different business concepts (flight endpoints, flights paths, flight direction parsing)</li>\n<li>Cluttered logic is hard to read and maintain. Breaking it up into well-named variables, classes and methods helps fix this.</li>\n<li>Use of noun-named method (<code>Consonants()</code> as opposed to <code>Consonants</code> property or <code>MakeConsonants()</code> method)</li>\n</ol>\n\n<p>I originally wrote out step-by-step instructions to address these concerns, but it got too long, so I'm instead only including a suggested revision of your code with the above problems addressed:</p>\n\n<pre><code>public class Flight\n{\n private const char endpointSeparator = '-';\n private string direction;\n\n public Flight(string direction)\n {\n this.direction = direction;\n }\n\n public string Consonants\n {\n get\n {\n return String.Join(endpointSeparator.ToString(), EndpointAbbreviations);\n }\n }\n\n private IEnumerable<string> EndpointAbbreviations\n {\n get\n {\n return EndpointNames.Select(Abbreviate);\n }\n }\n\n private string[] EndpointNames\n {\n get\n {\n return direction.Split(endpointSeparator);\n }\n }\n\n private static string Abbreviate(string endpointName)\n {\n var endpoint = new FlightEndpoint(endpointName);\n return endpoint.Abbreviation;\n }\n}\n\npublic class FlightEndpoint\n{\n private readonly string name;\n\n public FlightEndpoint(string name)\n {\n this.name = name;\n }\n\n public string Abbreviation\n {\n get\n {\n return new string(UppercaseFirstAndLastConsonants);\n }\n }\n\n private char[] UppercaseFirstAndLastConsonants\n {\n get\n {\n IEnumerable<char> uppercaseConsonants = UppercaseConsonants;\n return new[] { uppercaseConsonants.First(), uppercaseConsonants.Last() };\n }\n }\n\n private IEnumerable<char> UppercaseConsonants\n {\n get\n {\n return UppercaseName.Where(IsConsonant);\n }\n }\n\n private string UppercaseName\n {\n get\n {\n return name.ToUpper();\n }\n }\n\n private static bool IsConsonant(char uppercaseCharacter)\n {\n return !IsVowel(uppercaseCharacter);\n }\n\n private static bool IsVowel(char uppercaseCharacter)\n {\n return \"AEIOU\".Contains(uppercaseCharacter);\n }\n}\n</code></pre>\n\n<p>Notes about the above code:</p>\n\n<ol>\n<li>Methods are organised for easy reading from top to bottom.</li>\n<li>Methods are kept short for better code readability</li>\n</ol>\n\n<p>Further suggestions:</p>\n\n<ol>\n<li>Create a <code>FlightDirection</code> or <code>FlightPath</code> class that consists of the <code>FlightEndpoint</code>s and the <code>Consonants</code> operation to separate the operation from the <code>direction</code> parsing logic.</li>\n<li>Extract out the code related to vowels and letter case if it will or could be used in other code.</li>\n<li>Rename <code>Consonants</code> since it reads as if it gets <em>all</em> consonants. Perhaps there is a business term that is more clear, such as <code>Abbreviation</code> or <code>ShortName</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:28:50.090",
"Id": "39631",
"ParentId": "39611",
"Score": "5"
}
},
{
"body": "<p>This code will \"work\", and in any imaginable sane use case it will work \"fast enough\". So I feel like my comments are pedantic; nevertheless:</p>\n\n<h2>Variable declarations</h2>\n\n<p>I think this is often a matter of opinion, but I prefer to use <code>var</code> unless absolutely necessary. Specifying type is usually redundant and distracting, whereas <code>var</code> conveys what the programmer actually meant: \"Just make me a variable, I don't care about the type, figure out yourself which one is correct, you have type safety anyway!\"</p>\n\n<pre><code>var starting = direction.Split('-')[0];\nvar destination = direction.Split('-')[1];\n</code></pre>\n\n<p>The compiler will use C#'s strict typing features to resolve the appropriate type for each variable (based on return type of <code>string.Split</code> in this case) and replace the <code>var</code> with <code>string</code> before generating CIL bytecode. Note that this is <em>at compile time</em> - it is just syntactic sugar with no bearing on program logic, unlike, say, JavaScript's <code>var</code>.</p>\n\n<h2>Calling <code>split</code> twice</h2>\n\n<p>You split <code>direction</code> twice. Since the algorithm isn't \"split string, take first part, split string, take second part\", the implementation is confusing to read. A more natural approach would be \"split string, distribute two parts accordingly\":</p>\n\n<pre><code>var parts = direction.Split('-');\nvar starting = parts[0];\nvar destination = parts[1];\n</code></pre>\n\n<p>This inflates your line count a bit, but it is more intuitive, and slightly more efficient (especially if there were many tokens, the code was deep inside a loop and/or the splitting pattern was a complicated Regex that takes a long time to run). Plus, you can inspect the outcome of the split easily when debugging in Visual Studio by mousing over <code>parts</code>.</p>\n\n<h2>Inefficient consonant search</h2>\n\n<p>Your replace algorithm will run over the entire string. However, you don't actually care about the characters between the first and second consonants. You could implement a more appropriate algorithm:</p>\n\n<pre><code>i=0, j=0\nhead_found = false, tail_found = false\nwhile !(head_found | tail_found)\n if(!head_found)\n if(Is_consonant(s[i])) head_found = true;\n else i++\n if(!tail_found)\n if(Is_consonant(s[j])) tail_found = true;\n else j-- \nreturn [i, j]\n</code></pre>\n\n<p>Your current algorithm runs in linear time (proportional to length of input strings). The solution above runs in constant time (proportional to mean of the Poisson distribution describing the number of leading/trailing vowels in city names).</p>\n\n<p>For this particular case, you could probably get away with even simple recursive functions:</p>\n\n<pre><code>int Index_of_first_consonant(string s)\n if(Is_consonant(s.First())) return 0\n else return 1+Index_of_first_consonant(s.Substring(1))\n\nint Index_of_last_consonant(string s)\n if(Is_consonant(s.Last())) return s.Length-1\n else return Index_of_last_consonant(s.Take(s.Length-1))\n</code></pre>\n\n<h2>Inefficient lookup</h2>\n\n<p>For what you are doing, the typical solution is to use either <code>Dictionary</code> or <code>HashSet<char></code> which includes both lowercase and uppercase consonants (the extra space usage is trivial in this case). You will have to predefine it:</p>\n\n<pre><code>private static HashSet<char> consonants = new HashSet<char>{ 'B', 'b', 'C', 'c', 'D', 'd' /* TODO: include all consonants */ };\n</code></pre>\n\n<p>Unfortunately <code>var</code> cannot be used for fields. If you are lazy, you can add a static constructor for your class and populate this <code>consonants</code> programmatically, with your inefficient vowel exclusion method (efficiency won't matter because the static constructor will run only once per program execution). But you should still use a <code>HashSet</code> for tasks like these, which essentially test membership of a set.</p>\n\n<h2>Major bugs</h2>\n\n<p>Your code will crash for strings which don't have enough consonants. (Strangely named cities or erroneously provided null strings) You can fix extra whitespace with <code>myString.Trim()</code>, but that won't handle symbols (for example, one way of transliterating Cyrillic names can generate words ending with <code>'</code>).</p>\n\n<p>You also don't handle non-letters correctly. With your example input <code>London - Berlin</code>, I think the first consonant of the destination and the last consonant of the starting point will be returned as spaces.</p>\n\n<h2>Naming</h2>\n\n<p>The common convention is to use nouns for properties and fields, and verbs (often in the imperative) for methods. Also, your method <code>Consonants</code> doesn't actually produce the consonants, it produces a string describing first and last consonants. Therefore the name is a bit misleading, you might consider something like <code>Print_first_last_consonants</code>.</p>\n\n<h2>Return expression</h2>\n\n<p>My personal preference is to assign return values to an intermediate variable first.</p>\n\n<pre><code>var result = /* calculate result here */;\nreturn result;\n</code></pre>\n\n<p>This way, when your program crashes and you come across this method while trudging through the stack, it will be easier for you to decide if the error propagated to this method or not.</p>\n\n<p>Also, for the actual calculation, I would have used</p>\n\n<pre><code>startConsonants.First() + startConsonants.Last() + \"-\" + destConsonants.First() + destConsonants.Last()\n</code></pre>\n\n<p>since it is easier to read, unless you anticipate that you will be changing the output format drastically and/or frequently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:00:43.250",
"Id": "39637",
"ParentId": "39611",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T21:57:48.923",
"Id": "39611",
"Score": "12",
"Tags": [
"c#",
"beginner"
],
"Title": "Returning consonants of a plane's starting and ending points"
}
|
39611
|
<p>I've found a peace of code I've wrote not long ago. It is used to fetch some dictinary from DB table only once and then return it to requestors. Seems like I tryed to implement double-checked locking here. Is it correct? If not, what are the mistakes?</p>
<pre><code>package a.b.c.service.orders;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import a.b.c.dao.OrderStatusesDao;
import a.b.c.model.OrderStatuses;
@Component
public class OrderStatusesService {
@Autowired
private OrderStatusesDao orderStatusesDao;
private volatile Map<String, String> cached;
@Transactional(rollbackFor = Exception.class, readOnly = true)
public Map<String, String> getAllOrderStatuses() {
if (null == cached) {
synchronized (OrderStatusesService) {
if (null == cached) {
final List<OrderStatuses> orderStatuses = orderStatusesDao.getAll();
cached = new HashMap<String, String>();
for (OrderStatuses orderStatus : orderStatuses) {
cached.put(orderStatus.getCode(), orderStatus.getName());
}
}
}
}
return cached;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:05:14.977",
"Id": "66457",
"Score": "1",
"body": "See this video: http://www.youtube.com/watch?v=pi_I7oD_uGI#t=2228"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T19:12:12.327",
"Id": "66553",
"Score": "0",
"body": "Double checked locking is tricky. Have you made a benchmark to verify that always locking creates a performance problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T20:06:14.677",
"Id": "66558",
"Score": "0",
"body": "I do not face any problems. Just curious if the code is correct."
}
] |
[
{
"body": "<p>There are a few reasons why double-checked locking does not always work in Java. There are a number of blogs with more detail, but I quite like <a href=\"http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html\">this one</a> and <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\">this one</a>.</p>\n\n<p>Now, your code contains a volatile declaration for <code>cached</code> which, in certain conditions can mitigate the problem, but it is not a complete solution. You can still have cases where the <code>cached</code> variable is set in one thread, but another thread reads it before it is completely initialized. Since the values in the <code>cached</code> are not volatile, you will have problems still. Also, they depend on <code>orderStatusesDao</code> which is not volatile either...</p>\n\n<p>With Java5's changes to the memory model, you can probably use a 'helper' variable to initialize the data... something like:</p>\n\n<pre><code> Map<String,String> helper = new HashMap<String, String>();\n for (OrderStatuses orderStatus : orderStatuses) {\n helper.put(orderStatus.getCode(), orderStatus.getName());\n }\n cached = helper;\n</code></pre>\n\n<p>Using the helper ensures that the cached instance is fully assigned before it gets set.</p>\n\n<p>This all seems very complicated.... and all to save a micro-synchronization.</p>\n\n<p>With the advent of Java6 and enums, there are a few really good ways to create thread-safe lazy-initialized values, but your case is somewhat more complicated by the <code>orderStatusesDao.getAll();</code> required for initialization.</p>\n\n<p>As an 'aside' comment, I am concerned by this line:</p>\n\n<pre><code>synchronized (OrderStatusesService) { ...\n</code></pre>\n\n<p>The line suggests you have a variable called <code>OrderStatusesService</code> which is the exact same name as the class <code>OrderStatusesService</code>.... or is the synchronization supposed to be on <code>OrderStatusesService.class</code>?</p>\n\n<p>In your case above, I would probably be satisfied with a simple/standard synchronization block and no volatile declaration. The lock-wait time will be very minimal.</p>\n\n<p>Alternatively, I would consider an optimistic system using AtomicReferences, for example:</p>\n\n<pre><code>Map<String, String> cached = atomicref.get();\nif (cached != null) {\n return cached;\n}\ncached = new HashMap....;\n// populate cached.....\nif (atomicref.compareAndSet(null, cached)) {\n // we were the first thread to populate, great:\n return cached;\n}\n// return the value that the winning thread created.\nreturn atomicref.get();\n</code></pre>\n\n<p>in the above system, the first thread to 'set' the cached value will have it's instance used by every other thread. It is possible that multiple threads may be initializing their values at the same time, but they will all defer back to the winning-thread instance if they don't win. Once the instance is set, all threads will use that instance and there will be only fast atomic locking.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T19:59:46.683",
"Id": "66557",
"Score": "0",
"body": "+1 for using compare-and-set to ensure that every caller gets the same map even when multiple threads initialize it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T01:15:15.437",
"Id": "39624",
"ParentId": "39617",
"Score": "5"
}
},
{
"body": "<p>This is <em>not</em> thread-safe, but it's close. The problem is that you add elements to the map <em>after</em> storing its reference in <code>cached</code>, making the <em>incomplete</em> map available to other callers until initialization is complete. The first step is to move the map building into a separate method.</p>\n\n<pre><code>private Map<String, String> loadAllOrderStatuses() {\n final List<OrderStatuses> orderStatuses = orderStatusesDao.getAll();\n final HashMap<String, String> result = new HashMap<String, String>();\n\n for (OrderStatuses orderStatus : orderStatuses) {\n result.put(orderStatus.getCode(), orderStatus.getName());\n }\n return result;\n}\n</code></pre>\n\n<p>Returning the raw map to clients can also be dangerous since any caller is free to add elements to it which may or may not be seen by other threads or even corrupt the map's internal structure as viewed by other threads. If you do not control all callers of this method, you may wrap the result in an unmodifiable version at the end of the above method.</p>\n\n<pre><code>return Collections.unmodifiableMap(result);\n</code></pre>\n\n<p>With this, as long as you're running on Java 1.5+ where <code>volatile</code> is well-defined, it should be thread-safe. However, it can still be improved slightly. Volatile fields force a memory barrier on <em>every</em> access so it's better to write the computed value only once and minimize reads in the already-initialized code path. This can be done using a local variable as seen in the <a href=\"http://www.youtube.com/watch?v=pi_I7oD_uGI#t=2228\" rel=\"nofollow noreferrer\">Effective Java Reloaded</a> presentation linked by Banthar.</p>\n\n<pre><code>@Transactional(rollbackFor = Exception.class, readOnly = true)\npublic Map<String, String> getAllOrderStatuses() {\n Map<String, String> result = cached;\n if (null == result) {\n synchronized (this) {\n result = cached;\n if (null == result) {\n cached = result = loadAllOrderStatuses();\n }\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>Finally, you're invoking the transaction advice on every call even though it's only needed on the first for initialization. You can avoid this by moving <code>loadAllOrderStatuses</code> along with <code>@Transactional</code> to a separate bean. There are <a href=\"https://stackoverflow.com/a/8233459/285873\">other</a> <a href=\"https://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo\">workarounds</a> if this seems too much like overkill.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T01:21:44.123",
"Id": "39625",
"ParentId": "39617",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39625",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:13:14.030",
"Id": "39617",
"Score": "6",
"Tags": [
"java",
"multithreading",
"concurrency"
],
"Title": "Double checked locking 101"
}
|
39617
|
<p>Looking for general feedback and praise. This is for learning an not implementation as I would expect the built is sort algos to be much faster.</p>
<p>Addressed issues here:</p>
<p><a href="https://codereview.stackexchange.com/questions/38651/a-package-for-sort-algorithms">A package for sort algorithms</a></p>
<pre><code>/***************************************************************************************************
**ALGORITHMS
***************************************************************************************************/
// self used to hold client or server side global
(function (self) {
"use strict";
// holds (Pub)lic properties
var Pub = {},
// holds (Priv)ate properties
Priv = {},
// holds "imported" library properties
$A;
(function manageGlobal() {
// Priv.g holds the single global variable, used to hold all packages
Priv.g = '$A';
if (self[Priv.g] && self[Priv.g].pack && self[Priv.g].pack.utility) {
self[Priv.g].pack.algo = true;
$A = self[Priv.g];
} else {
throw new Error("algo requires utility module");
}
}());
Pub.swap = function (arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
// checks to see if sorted
Pub.isSorted = function (arr) {
var i,
length = arr.length;
for (i = 1; i < length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
};
// repeatedly orders two items ( a bubble ) at a time
Pub.bubbleSort = function (arr) {
var index_outer,
index_inner,
swapped = false,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
swapped = false;
for (index_inner = 0; index_inner < length - index_outer; index_inner++) {
if (arr[index_inner] > arr[index_inner + 1]) {
Pub.swap(arr, index_inner, index_inner + 1);
swapped = true;
}
}
if (!swapped) {
break;
}
}
return arr;
};
// repeatedly finds minimum and places it the next index
Pub.selectionSort = function (arr) {
var index_outer,
index_inner,
index_min,
length = arr.length;
for (index_outer = 1; index_outer < length; index_outer++) {
index_min = index_outer;
for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
if (arr[index_inner] < arr[index_min]) {
index_min = index_inner;
}
}
if (index_outer !== index_min) {
Pub.swap(arr, index_outer, index_min);
}
}
return arr;
};
// repeatedly places next item in correct spot using a "shift"
Pub.insertionSort = function (arr) {
var index_outer,
index_inner,
value,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
value = arr[index_outer];
// JavaScript optimization - index_inner >=0 is removed
// as the array index will return undefined for a negative index
for (index_inner = index_outer - 1; (arr[index_inner] > value);
index_inner--) {
arr[index_inner + 1] = arr[index_inner];
}
arr[index_inner + 1] = value;
}
return arr;
};
// module complete, release to outer scope
self[Priv.g] = $A.extendSafe(self[Priv.g], Pub);
}(this));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T16:37:08.477",
"Id": "66523",
"Score": "0",
"body": "Is your code faster than the built-in `sort()`, and if not, what is the purpose of this library ?"
}
] |
[
{
"body": "<p>What is the reason for performing internal initialization inside the <code>manageGlobal</code> function? You're already inside a function, and you're operating on its local variables.</p>\n\n<p>Here are some thoughts on the insertion sort (chosen at random):</p>\n\n<ul>\n<li><p>You can start <code>index_outer</code> at <code>1</code> since the inner loop is empty at <code>0</code>.</p></li>\n<li><p>Use camelCase for variable and function names</p></li>\n<li><p>Try to find names that are more descriptive. For example, <code>upperIndex</code> since it's the moving upper bound and <code>shiftIndex</code> since it's the index of the element to shift up.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:27:35.473",
"Id": "39623",
"ParentId": "39619",
"Score": "2"
}
},
{
"body": "<p>Apart from the points I already mentioned in your previous post, I would like to point out that the JavaScript way of preserving the global object is not passing it as a parameter, but using <code>Function.prototype.call</code>, effectively turning your last line into</p>\n\n<pre><code> }).call(this);\n</code></pre>\n\n<p>Also note that this code breaks if not executed in the global scope - which may always be the case if you use module packaging scripts such as RequireJS.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T16:46:19.583",
"Id": "66530",
"Score": "0",
"body": "What is your reason for this? Functionally there is no difference between using `call()` vs the way I do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T18:27:47.863",
"Id": "66545",
"Score": "1",
"body": "Mainly everyone reading your code will immediately know what `this` means whereas people who do not know Python might not recognize `self`. Additionally it's a convention thing, it's the way big libraries do it. Also, you should stick to the name the language you use uses, i.e. you could change every `self` to a `this` in Python, but you don't - because it's counter intuitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T18:30:24.533",
"Id": "66546",
"Score": "0",
"body": "jQuery does it the way I do it - just FYI."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T19:48:11.233",
"Id": "66556",
"Score": "0",
"body": "Ultimately it's of course your choice, but jQuery doesn't change the 'name' of the global object. Inside the closure `window` is still `window`. In your situation, where your library could also be used on the server side and the global object isn't `window`, I would just stick to `this` and the most concise way to do that is to use `call` IMHO. And you're asking for our opinion on your code ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T22:02:17.190",
"Id": "66993",
"Score": "0",
"body": "O.K. will update."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:49:42.513",
"Id": "39640",
"ParentId": "39619",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39623",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:44:26.230",
"Id": "39619",
"Score": "2",
"Tags": [
"javascript",
"sorting"
],
"Title": "A package for sort algorithms - v2"
}
|
39619
|
<p>This is basically the registry pattern and a pub/sub event system.</p>
<p>Very simple and minimalist. Looking for general feedback.</p>
<pre><code>/***************************************************************************************************
**COMMS
- provides registry and event system
- reduces dependencies
***************************************************************************************************/
// self used to hold client or server side global
(function (self) {
"use strict";
// holds (Pub)lic properties
var Pub = {},
// holds (Priv)ate properties
Priv = {},
// holds "imported" library properties
$A;
(function manageGlobal() {
// Priv.g holds the single global variable, used to hold all packages
Priv.g = '$A';
if (self[Priv.g] && self[Priv.g].pack && self[Priv.g].pack.utility) {
self[Priv.g].pack.comms = true;
$A = self[Priv.g];
} else {
throw new Error("comms requires utility module");
}
}());
Pub.Reg = (function () {
var publik = {},
register = {};
publik.get = function (key) {
return register[key];
};
publik.set = function (key, value) {
register[key] = value;
};
publik.setMany = function (o) {
$A.someKey(o, function (val, key) {
register[key] = val;
});
};
publik.getMany = function () {
return register;
};
return publik;
}());
Pub.Event = (function () {
var publik = {},
events = {};
publik.add = function (name, callback) {
if (!events[name]) {
events[name] = [];
}
events[name].push(callback);
};
publik.remove = function (name, callback) {
if (name && callback) {
delete events[name][callback];
} else if (name) {
delete events[name];
}
};
publik.trigger = function (name) {
if (events[name]) {
$A.someIndex(events[name], function (val) {
val();
});
}
};
return publik;
}());
self[Priv.g] = $A.extendSafe(self[Priv.g], Pub);
}(this));
</code></pre>
|
[] |
[
{
"body": "<p>It looks good overall IMO. I won't comment on the bootstrap code as I'm not familiar with your library, but I would change a few things. Inside the closures that you create you could simply return the public object, without defining <code>publik</code>, it looks a bit cleaner. Then I added some annotation and changed the control flow a bit: </p>\n\n<pre><code>Pub.Reg = (function() {\n var register = {};\n return {\n get: function(key) {\n return register[key];\n },\n set: function(key, value) {\n register[key] = value;\n },\n setMany: function(o) {\n $A.someKey(o, function (val, key) {\n register[key] = val;\n });\n },\n getMany: function() {\n return register;\n }\n };\n}());\n\nPub.Event = (function() {\n var events = {};\n return {\n add: function(name, callback) {\n // A bit more concise\n (events[name] = events[name]||[]).push(callback);\n },\n remove: function(name, callback) {\n // It's faster to set the value to `null`\n // than using the `delete` operator\n // but this depends on your use case;\n // the properties would still show up\n // in a `for..in` loop, but it's fine\n // if you use it merely as a dictionary\n if (!callback) {\n events[name] = null;\n return;\n }\n events[name][callback] = null;\n },\n trigger: function(name) {\n if (events[name]) {\n $A.someIndex(events[name], function (val) {\n val();\n });\n }\n }\n };\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:22:40.627",
"Id": "66472",
"Score": "0",
"body": "500! Congratulations!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:19:29.770",
"Id": "39630",
"ParentId": "39621",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39630",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:22:53.177",
"Id": "39621",
"Score": "1",
"Tags": [
"javascript",
"sorting"
],
"Title": "A package for communications between packages - v2"
}
|
39621
|
<p>This Scala code snippet is supposed to encode a SHA1 hash in base 62.</p>
<p>Can you find any issues? I'm asking since I might not be able to change the algorithm and, for example, fix issues in the future.</p>
<p>I'd like to be able to also implement it in JavaScript in the future.</p>
<pre><code>def mdSha1() = java.security.MessageDigest.getInstance("SHA-1") // not thread safe
def hashSha1Base62DontPad(text: String): String = {
val bytes = mdSha1().digest(text.getBytes("UTF-8"))
val bigint = new java.math.BigInteger(1, bytes)
val result = encodeInBase62(bigint)
result
}
private val Base62Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def encodeInBase62(number: BigInt): String = {
// Base 62 is > 5 but < 6 bits per char.
var result = new StringBuilder(capacity = number.bitCount / 5 + 1)
var left = number
do {
val remainder = (left % 62).toInt
left /= 62
val char = Base62Alphabet.charAt(remainder)
result += char
}
while (left > 0)
result.toString
}
</code></pre>
|
[] |
[
{
"body": "<p>It is 'standard' to have <code>0-9</code> at the beginning of the 'alphabet' for numbers....</p>\n\n<p>I would have suggested that you use the native functionality in BigInteger to convert the value to a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toString%28int%29\" rel=\"nofollow\">String in any given radix</a>, but unfortunately, it does not support more than radix 36. Still, you should follow that standard and start with <code>0-9</code> instead of ending with it.</p>\n\n<p>I would also suggest two things:</p>\n\n<ul>\n<li><p>you should convert the alphabet to an array immediately:</p>\n\n<pre><code>private val Base62Alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\".toCharArray()\n</code></pre></li>\n<li><p>you should not have the magic number '62' in your code, but should base it off the array size:</p>\n\n<pre><code>private val Radix = Base62Alphabet.length\n</code></pre>\n\n<p>your code then becomes:</p>\n\n<pre><code>val remainder = (left % Radix).toInt\nleft /= Radix\n</code></pre></li>\n</ul>\n\n<p>Finally, I don't like that you have variable-length results from the conversion. You should ensure that all hashes of data with the same length have the same length of output... -left-padding with <code>0</code> as needed. It <strong>is</strong> possible for something to hash to 0x0000000000 (hex).... which will give you 0-value <code>number.bitCount</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T00:45:46.017",
"Id": "66589",
"Score": "0",
"body": "Thanks! Concerning the alphabet, Base64 uses \"ABCD...abcd...0123+/\" rather than \"0123...ABC...abc+/\" [according to Wikipedia](http://en.wikipedia.org/wiki/Base64). I was thinking \"Base64 but without the two last characters\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T00:49:26.857",
"Id": "66591",
"Score": "0",
"body": "@KajMagnus you should be aware that if you were to use Base64 instead, it **will** be faster, and the bit-manipulations are much easier (and there are some easy-to-use libraries for it already)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T02:20:54.887",
"Id": "66606",
"Score": "1",
"body": "On my computer, SHA1 + Base62 is 2.6 times slower than SHA1 + Base64. And running SHA1 + Base64 takes 5 microseconds. — I'll probably generate a URL safe base 64 string instead, and strip any '-'; that actually works fine in my particular use case, and is faster and simpler."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:14:22.397",
"Id": "39629",
"ParentId": "39627",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39629",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T02:56:52.933",
"Id": "39627",
"Score": "3",
"Tags": [
"scala",
"converting"
],
"Title": "Is this base 62 encoding algorithm okay?"
}
|
39627
|
<p>I'm working on the following interview practice problem, and got the following solution, which runs in worst case <code>n!</code> time (best case constant), and I'm trying to optimize it.</p>
<p>Can you offer any suggestions to go about this? I think it should be able to be reduced down to <code>quadratic</code>, if not <code>nlogn</code>, but I'm not entirely sure of an approach to achieve this.</p>
<pre><code>/** Write a function to check if any three numbers in an array sum to a given number, X */
public class SumToNum {
public static void main(String[] args) {
int[] test = {1,8,2,3,11,4};
System.out.println(threeSumTo(test, 6)); //Returns true
}
public static boolean threeSumTo(int[] array, int x) {
List<Integer> items = new LinkedList<>();
for (int i : array) { items.add(i); }
return threeSumTo(items, x, 3);
}
public static boolean threeSumTo(List<Integer> items,int numRemaining, int count) {
if (numRemaining == 0) {
return true;
}
if (count == 0){
return false;
}
for (int i = 0; i < items.size(); i++) {
int curr = items.remove(i);
if (curr <= numRemaining) {
boolean result = threeSumTo(items, numRemaining - curr, count - 1);
if (result) {
return result;
}
}
items.add(i, curr);
}
return false;
}
}
</code></pre>
<hr>
<p><strong>EDIT:</strong> Ok, here's a solution based on Rafa's advice, using some more clever deduction. Basically, I'm just reducing it down to two integers that sum up to a number, and doing this for every number in the array. It looks like it works as intended, but in N<sup>2</sup> worst case time this time.It also assumes the array is sorted, otherwise, as answered below, the problem is NP-Complete. Thanks for the help. </p>
<pre><code>public static boolean threeSumTo(int[] array, int x) {
for (int i = 0; i < array.length; i++) {
boolean result = twoSumTo(array, x - array[i], i);
if (result) {
return result;
}
}
return false;
}
private static boolean twoSumTo(int[] array, int x, int low) {
int high = array.length - 1;
while (low < high) {
if (array[low] + array[high] == x) {
return true;
}
if (array[low] + array[high] > x) {
high--;
} else {
low++;
}
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:30:43.243",
"Id": "66474",
"Score": "0",
"body": "First think I would do is, check total of number from array that is less than the given number (in your above case, `6`). If total number is less than `3`, then return `false`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T04:08:45.820",
"Id": "66484",
"Score": "0",
"body": "You should take a moment and read through this question/answer set.... [Finding pair of sum in sorted array](http://codereview.stackexchange.com/questions/38994/finding-pair-of-sum-in-sorted-array)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T04:13:44.603",
"Id": "66485",
"Score": "0",
"body": "Haha the final linear solution proposed is the exact thing I'm doing to solve the twoSum problem."
}
] |
[
{
"body": "<p>First, make the array constant. There is no need to change this array or use any other data structure.</p>\n\n<p>You want an outer loop that does something like <code>for (int i : array)</code>.</p>\n\n<p>Inside that outer loop, have another loop like <code>for( (int j = i + 1; j < max; j++)</code>.</p>\n\n<p>These loops give you the first 2 numbers out of 3. If the first 2 numbers are greater than <code>X</code> then the 3 numbers can't be equal to <code>X</code>. To save time do an <code>if( array[i] + array[j] <= x) {</code> thing.</p>\n\n<p>Finally you need an inner loop for the possible third numbers, like <code>for( (int k = k + 1; k < max; k++)</code> with a something like <code>if( array[i] + array[j] + array[k] == x) return true;</code> inside it.</p>\n\n<p>That's about it - 3 loops and 2 <code>if</code> statements.</p>\n\n<p><em>Note: I don't remember how to Java at the moment - syntax above might be wrong but you should hopefully understand it anyway. ;-)</em></p>\n\n<p><em>Note 2: I don't know if it's possible for the numbers to be negative (they are <code>int</code> but Java doesn't support <code>unsigned int</code>). If it is possible then remove/ignore the <code>if( array[i] + array[j] <= x) {</code> part (because it'd be wrong in that case).</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:37:44.227",
"Id": "66475",
"Score": "0",
"body": "The general the concepts you describe are fine, but you should be careful about the details... with `for (int i : array)` your `i` will contain the values, not the indexes of the array, and then using `for( (int j = i + 1; j < max; j++)` the j value will likely be broken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:40:27.660",
"Id": "66476",
"Score": "0",
"body": "@rolfl: Heh - I'm an assembly/C programmer. I was taught Java and messed with it a little, but never did find a good use for it and forgot most of it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:31:23.050",
"Id": "39632",
"ParentId": "39628",
"Score": "1"
}
},
{
"body": "<p>Hate to say it, but you have chosen some pretty slow data structures to use for your code....</p>\n\n<p>Your input data is in an <code>int[]</code> array. This is a great data structure. You convert those values to a List, which is not as nice (more memory, slower because of data conversions, etc.), but, the real kicker, is that you use a <code>LinkedList</code>....</p>\n\n<p>The <code>LinkedList</code> implementation has an <em>O(n)</em> access time... so, doing things like <code>remove(i)</code> and <code>add(i, curr)</code> require a scan of the list to find the position.</p>\n\n<p>next up, I don't think your solution using recursion is the easiest, or the fastest.</p>\n\n<p>In your case, there are really two strategies for this. The first strategy is to sort the data ( <em>O(n log(n))</em> ) and then do some smart looping. The second is a naive approach. The naive approach is actually quite simple to understand:</p>\n\n<pre><code>for (int i = 0; i < array.length; i++) {\n for (int j = i + 1; j < array.length; j++) {\n for (int k = j + 1; k < array.length; k++) {\n if (array[i] + array[j] + array[k] == target) {\n return true;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T04:01:36.627",
"Id": "66483",
"Score": "0",
"body": "Got up a n^2 I believe. Should be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-27T19:14:34.383",
"Id": "365687",
"Score": "0",
"body": "This is `O(n3)` runtime."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:35:20.780",
"Id": "39633",
"ParentId": "39628",
"Score": "4"
}
},
{
"body": "<p>Another trick that might help if the pool of numbers is large and rather random: partition it into two pools, one of even numbers and other of odds. If the sum is even, you will need either zero or two odds. If the sum is odd, you will need either one or three odds.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:38:25.610",
"Id": "39634",
"ParentId": "39628",
"Score": "3"
}
},
{
"body": "<p>This is a specialised instance of the <a href=\"http://en.wikipedia.org/wiki/Subset_sum_problem\" rel=\"nofollow noreferrer\">Subset sum problem</a>, which is NP-Complete in the general case. </p>\n\n<p>Of course, when working with a small subset size that is known in advance, we can significantly cut down on the running time (at worst checking <code>C{n, k}</code> values, where <code>n</code> is the number of values in the search space and <code>k</code> is the size of the subset we're looking for). The <code>O(n^3)</code> naive algorithm here is clearly much better than the <code>O(n!)</code> running time of your original algorithm. However, we can get this down to <code>O(n^2 log n)</code> pretty easily. Firstly, sort the original array:</p>\n\n<pre><code>private int[] values;\n\npublic Subset(int[] v)\n{\n values = Arrays.copyOf(v, v.length);\n Arrays.sort(values);\n}\n</code></pre>\n\n<p>Now, we can loop over each pair of indices in the array, and binary search for the difference between the calculated sum and the desired number:</p>\n\n<pre><code>public boolean sumsTo(int num)\n{\n int sum = 0;\n for(int i = 0; i < values.length - 1; ++i) { \n for(int j = i+1; j < values.length; ++j) {\n sum = values[i] + values[j];\n if(Arrays.binarySearch(values, num - sum) > 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>In fact, with a bit more stuffing around, we can get this down to <code>O(n^2)</code>. There is an approach to do so outlined <a href=\"https://stackoverflow.com/questions/2070359/finding-three-elements-in-an-array-whose-sum-is-closest-to-an-given-number\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T04:54:15.363",
"Id": "39636",
"ParentId": "39628",
"Score": "10"
}
},
{
"body": "<p>Also have a look at my solution (both naive and something with O(N^2)):\n//Note: you could also first sort in naive solution.\n import java.util.ArrayList;\n import java.util.Arrays;\n import java.util.List;</p>\n\n<pre><code>/**\n * Created by mona on 5/25/16.\n */\n\n//check to see if sum of three numbers in array is equal to sum\npublic class SumOfThree {\n\n public static List<List<Integer>> sumOfThreeNaive(int[] a, int sum){\n List<List<Integer>> result = new ArrayList<>();\n for (int i=0; i<a.length-2; i++){\n for (int j=i+1; j<a.length-1; j++){\n for (int k=j+1; k<a.length; k++){\n if (a[i]+a[j]+a[k]==sum){\n result.add(Arrays.asList(a[i],a[j],a[k]));\n }\n }\n }\n }\n return result;\n }\n\n //first sort the array\n //start from the index after i and last index\n // move those indices towards each other\n public static List<List<Integer>> sumOfThree(int[] a, int sum){\n List<List<Integer>> result = new ArrayList<>();\n Arrays.sort(a);\n int l,r;\n for (int i=0; i<a.length-2; i++){\n l=i+1;\n r=a.length-1;\n while (l<r){\n if (a[i]+a[l]+a[r]==sum ){\n result.add((Arrays.asList(a[i],a[l], a[r])));\n l++;\n }\n else if (a[i]+a[l]+a[r]<sum){\n l++;\n }\n else{\n r--;\n }\n }\n }\n\n\n return result;\n }\n public static void main(String[] args){\n int[] a={1,3, 7, 8, 3, 9, 2, 4, 10};\n List<List<Integer>> triplets;\n //triplets=sumOfThreeNaive(a, 13);\n triplets=sumOfThree(a,13);\n for (List<Integer> list : triplets){\n for (int triplet: list){\n System.out.print(triplet+\" \");\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<p>//Also you could use hashset to only consider unique numbers depending on the further problem statements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-02T03:17:42.310",
"Id": "398857",
"Score": "1",
"body": "// doesn't work for new int[]{1,2,3,4} target 8"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-25T07:17:16.763",
"Id": "129253",
"ParentId": "39628",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "39636",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T03:13:44.200",
"Id": "39628",
"Score": "11",
"Tags": [
"java",
"optimization",
"interview-questions",
"complexity"
],
"Title": "Checking if three numbers sum to a given number"
}
|
39628
|
<p>RakNet is a C++ class library that provides UDP and reliable TCP transport. It contains several core systems that rely on the transport layer: object replication; Remote procedure call in C++ using Boost C++ Libraries; VoIP supporting FMOD, DirectSound, and PortAudio; NAT traversal; and Patch.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:19:50.910",
"Id": "39638",
"Score": "0",
"Tags": null,
"Title": null
}
|
39638
|
RakNet is a cross platform, open source, C++ networking engine for game programmers by Jenkins Software
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T05:19:50.910",
"Id": "39639",
"Score": "0",
"Tags": null,
"Title": null
}
|
39639
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.