body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>After working on it, my regenerating reserve vector may not be so bad after all. (In <a href="https://stackoverflow.com/questions/44326712/speeding-vector-push-back">this stackoverflow question</a>, I presented a vector with a regenerating reserve, faster at <code>push_back</code> when reserve can't be predicted).</p>
<p>Deque may be cool, but the vector is faster. So, I ameliorated my Vector, with two reserves: one before the begin and another after the end, thus, enabling <code>push_front</code> in a vector very quickly (<code>push_back</code> is still better than a normal vector).</p>
<p>With a RESA of 8192, and 1000 <code>push_front</code>, I had this results (computer is a Lenovo Think Center):</p>
<p>Duration of old <code>push_front</code> == 199 ticks (<code>insert(v.begin () , s)</code>)</p>
<p>Duration of new <code>push_front</code> == 5 ticks</p>
<p>What do you think about it?</p>
<pre><code>#ifndef __VECTOR2_HPP
#define __VECTOR2_HPP
class Concept {
public :
Concept () {}
~Concept () {}
enum const_e { //ok uw : PS = 512, FS 1024
RESA = 8192
};
};
#include <vector>
#include <iostream>
#include "Concept.hpp"
#include <exception>
#include <algorithm>
template <typename T>
class Vector : public std::vector<T> {
public :
class Error : public std::exception {
public :
Error (std::string val = "") throw () : val_ (val) {}
~Error () throw () {}
const char* what () throw () {
std::string s ("Vector Error :");
s += val_;
return s.c_str();
}
private :
std::string val_;
};
typename std::vector<T>::iterator begin () {
typename std::vector<T>::iterator i (std::vector<T>::begin ());
i += lresa_;
return i;
}
typename std::vector<T>::iterator end () {
typename std::vector<T>::iterator i (std::vector<T>::end ());
i -= rresa_;
return i;
}
typename std::vector<T>::const_iterator begin () const {
typename std::vector<T>::const_iterator i (std::vector<T>::begin ());
i += lresa_;
return i;
}
typename std::vector<T>::const_iterator end () const {
typename std::vector<T>::const_iterator i (std::vector<T>::end ());
i -= rresa_;
return i;
}
typename std::vector<T>::reverse_iterator rbegin () {
typename std::vector<T>::reverse_iterator i (std::vector<T>::rbegin ());
i += rresa_;
return i;
}
typename std::vector<T>::reverse_iterator rend () {
typename std::vector<T>::reverse_iterator i (std::vector<T>::rend ());
i -= lresa_;
return i;
}
typename std::vector<T>::const_reverse_iterator rbegin () const {
typename std::vector<T>::const_reverse_iterator i (std::vector<T>::rbegin ());
i += rresa_;
return i;
}
typename std::vector<T>::const_reverse_iterator rend () const {
typename std::vector<T>::const_reverse_iterator i (std::vector<T>::rend ());
i -= lresa_;
return i;
}
Vector () : std::vector<T> (2*(size_t) Concept::RESA, T()), lresa_ ((size_t) Concept::RESA), rresa_ ((size_t) Concept::RESA) {
}
size_t size () const {
size_t s (std::vector<T>::size ());
s -= lresa_;
s -= rresa_;
return s;
}
Vector (int n, T t0) : std::vector<T> (n + 2*(size_t) Concept::RESA, t0), lresa_ ((size_t) Concept::RESA), rresa_ ((size_t) Concept::RESA) {
}
Vector (const Vector& v) : std::vector<T> (v), lresa_ (v.lresa_), rresa_ (v.rresa_) {
}
bool operator == (const Vector& v) const {
return std::equal (begin (), end (), v.begin ());
}
bool operator != (const Vector& v) const {
return !operator == (v);
}
T& operator [] (const size_t &s) {
return std::vector<T>::operator [] (s+lresa_);
}
void push_front (const T& t) {
if (!lresa_) {
std::vector<T>::insert (std::vector<T>::begin (), (size_t) Concept::RESA, t);
lresa_ = (size_t) Concept::RESA;
}
typename std::vector<T>::iterator i (std::vector<T>::begin ());
i += lresa_ -1;
*i = t;
--lresa_;
}
void push_back (const T& t) {
if (!rresa_) {
std::vector<T>::insert (std::vector<T>::end (), (size_t) Concept::RESA, t);
rresa_ = (size_t) Concept::RESA;
}
typename std::vector<T>::iterator i (std::vector<T>::end ());
i -= rresa_;
*i = t;
--rresa_;
}
//can be optimized,but that s not the topic
Vector& operator = (const Vector& v) {
std::vector<T>::operator = (v);
lresa_ = v.lresa_;
rresa_ = v.rresa_;
return *this;
}
//intelligent resize to do
//at the moment just stupid
void resize (size_t n) {
std::vector<T>::resize (n + lresa_ + rresa_);
}
private :
size_t lresa_;
size_t rresa_;
};
#endif
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-12T23:37:28.770",
"Id": "408758",
"Score": "3",
"body": "It cannot be O(1) as you sometime need to grow the vector and move items.. Maybe **amortized O(1)**?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T01:26:38.223",
"Id": "408764",
"Score": "3",
"body": "It would help to add links to your previous question(s). Also, it's unclear what `Concept.hpp` is; without it, we can't tell what `Concept::RESA` is. (\"RESA\" is not an obvious acronym; and then you use it again in `lresa_` and `rresa_`. I don't know what those identifiers are meant to signify.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T01:41:35.183",
"Id": "408765",
"Score": "0",
"body": "Concept::RESA is a constant that should be smaller than stack size. It's the only thing declared in Concept.hpp. you may set it to 4 and test and then set it to 8K"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T01:42:20.217",
"Id": "408766",
"Score": "0",
"body": "lresa_ stands for left reserve and rresa_ stands for right reserve"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T20:27:51.127",
"Id": "418844",
"Score": "0",
"body": "You've been told repeatedly that invalidating answers by editing your question is not allowed, Since this question had been locked before and you invalidated the answers again, I have locked this post permanently. Thanks for understanding."
}
] | [
{
"body": "<p>Start by adding a type for you base class:</p>\n\n<pre><code>typedef std::vector<T> base;\n</code></pre>\n\n<p>This can be used to simplify many of your declarations within your code.</p>\n\n<p>Your various <code>begin</code>/<code>end</code> functions can be simplified</p>\n\n<pre><code>auto begin() {\n return base::begin() + lresa_;\n}\n</code></pre>\n\n<p>Unlike <code>vector</code>, your reserved areas contain default constructed objects. While this is not an issue for basic types like <code>int</code>, for more complicated types this can result in a performance hit and additional memory consumption.</p>\n\n<p>Your <code>operator==</code> compares the contents of the reserve areas, which can cause incorrect comparison results. An easy way this can happen is if an element is added then removed (although you do not have any form of remove). Your <code>reserve</code> can be used as a remove proxy, and will leave valid constructed objects in your reserve area if the vector is shrunk.</p>\n\n<p>You lack a <code>operator[] const</code> function.</p>\n\n<p>How will you handle a move constructor?</p>\n\n<p>You can improve your spacing/formatting. Having a space between a function name and the parenthesis is pretty uncommon and (IMHO) makes it harder to read. The overall indentation level is a bit shallow (3 or 4 spaces is more typical).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-31T18:35:51.077",
"Id": "411330",
"Score": "0",
"body": "For your comment about indentation, I like to guess what 's the line is doing without scrolling, and prefer a small indentation. Is this really important ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-31T19:09:31.187",
"Id": "411334",
"Score": "0",
"body": "I could do a operator [], but anyone here is able to do this. I prefered concentrate on method push_front"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T02:54:41.600",
"Id": "211403",
"ParentId": "211398",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>This is not what anyone would expect when using a <code>Vector</code>. It's closer to a <code>Deque</code>.</p></li>\n<li><p>Use <code>std::size_t</code>, not <code>size_t</code>.</p></li>\n<li><p>It looks like we're casting <code>Concept::RESA</code> to <code>size_t</code> every time it's used. Perhaps it should be declared as <code>std::size_t</code> to start with.</p></li>\n</ul>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/a/7110262/673679\">Inheritance is not a good fit here.</a></p>\n\n<ul>\n<li><p><code>std::vector</code> does not have a virtual destructor.</p></li>\n<li><p><code>std::vector</code> does not use virtual functions, so the added functions do <strong>not</strong> override the normal functionality. For example, any function that accepts a <code>std::vector<T> const&</code> will accept a <code>Vector<T></code> argument. It will then call the <code>std::vector</code> interface, and silently do the wrong thing.</p></li>\n<li><p><code>std::vector</code> has many other functions, e.g. <code>front()</code>, <code>back()</code>, <code>data()</code>, <code>cbegin()</code> etc. that are accessible to class users due to public inheritance, but will not do the expected thing when called, because they aren't overridden.</p></li>\n<li><p>Even if all these other functions are re-implemented, the interface of <code>std::vector</code> may change in future, for example adding a new function. New functions will be accessible, but do something unexpected / wrong.</p></li>\n</ul>\n\n<p>In short, we have to use composition here, not inheritance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T11:09:49.323",
"Id": "211412",
"ParentId": "211398",
"Score": "3"
}
},
{
"body": "<p>Your class requires T to be DefaultConstructible for an empty container. <code>std::vector</code> doesn't.</p>\n\n<p><code>__VECTOR2_HPP</code> - change to <code>VECTOR2_HPP__</code></p>\n\n<p>Don't publicly inherit from such complex classes as <code>std::vector</code>. For example, think of the results of calling <code>front()</code> on an object of your class.</p>\n\n<p>There is no reason for a hardcoded constant like <code>Concept::RESA</code>. Make it a parameter. Better yet, make the actual extent exponentially growing.</p>\n\n<p>There is no need for <code>rresa_</code>. The <code>std::vector</code> itself handles it better.</p>\n\n<p>Where do you use <code>Vector::Error</code>?</p>\n\n<p>No modifications of your container other than by just looping through <code>push_back()</code> and/or <code>push_front()</code> are thought out at all. The ones inherited from <code>std::vector</code> are broken, and even the ones written by yourself are going to lead to unexpected results with <code>T</code> being something like <code>std::shared_ptr</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T11:35:03.933",
"Id": "211414",
"ParentId": "211398",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-12T23:17:31.610",
"Id": "211398",
"Score": "-4",
"Tags": [
"c++",
"c++11"
],
"Title": "Making vector push-front improved to O(1) / 8192"
} | 211398 |
<p>I've been learning to code in my spare time for a couple of years. I have covered object oriented stuff before and can usually understand other people's object oriented code. This is the first time I've written an object oriented program from scratch.</p>
<p>It has all the functionality that I want and (hopefully) no mistakes - I have stress tested it.</p>
<p>However, I still feel the code is a bit dirty so I'd like some suggested improvements. Some areas that I feel I've gone wrong:</p>
<p>1, I have put too much functionality into the board class and not enough into the player class. Is this an issue?</p>
<p>2, It was relatively streamlined to begin with but then I started adding stuff to "make it look cool" such as a coin toss to decide who goes first and drawing the winning line on the board/displaying a victory message. This is all great but my code seems to have gotten less clean as the game loop function is a bit messy - any recommendations for how to repackage it?</p>
<p>3, Any other comments? StackExchange can be a very brutal place; please be gentle in your critique......</p>
<p>4, Any recommendations for a next project that would be slightly harder but still manageable for someone of my level.</p>
<p>My code:</p>
<pre><code>import random
import pygame
import itertools
# Initailize PyGame object
pygame.init()
DISPLAY_WIDTH = 600
DISPLAY_HEIGHT = 600
BLOCK_SIZE = 200
# Defining colors (rgb values)
BACKGROUND_COLOR = (0, 0, 0)
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
pink = (255, 20, 147)
cyan = (0, 255, 255)
gray = (128, 128, 128)
# Draw black rectangle to cover square numbers once played
def draw_rect(x, y, color = black, size=30, width = 0):
pygame.draw.polygon(gameDisplay, color, [(x-size, y-size), (x-size, y+size), (x+size, y+size), (x+size, y-size)], width)
def draw_wide_rect(x, y, color = black, size=30, width = 0):
pygame.draw.polygon(gameDisplay, color, [(x-3*size, y-2*size), (x-3*size, y+2*size), (x+3*size, y+2*size), (x+3*size, y-2*size)], width)
# How to draw naughts and crosses
def draw_naught(x, y, color, radius = 40, thickness = 20):
pygame.draw.circle(gameDisplay, color, (x,y), radius, thickness)
def draw_cross(x, y, color, closed = False, thickness = 20):
pygame.draw.lines(gameDisplay, color, closed, [(x-30, y-30), (x+30, y+30)], thickness)
pygame.draw.lines(gameDisplay, color, closed , [(x+30, y-30), (x-30, y+30)], thickness)
largefont = pygame.font.SysFont(None, 80)
player_font = pygame.font.SysFont('Comic Sans MS', 40)
def display_text(text, x, y, color):
text = largefont.render("{}".format(str(text)), True, color)
gameDisplay.blit(text, [x, y])
# Set up the display
gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT + 100))
pygame.display.set_caption("Naughts and Crosses")
clock = pygame.time.Clock()
# Draw the background grid
def drawGrid(w, rows, surface):
sizeBtwn = w // rows
x = 0
y = 0
pygame.draw.line(gameDisplay, white, (x,0),(x,w), 10)
pygame.draw.line(gameDisplay, white, (0,y),(w,y), 10)
for l in range(rows):
x = x + sizeBtwn
y = y + sizeBtwn
pygame.draw.line(gameDisplay, white, (x,0),(x,w), 10)
pygame.draw.line(gameDisplay, white, (0,y),(w,y), 10)
class Board:
def __init__(self, current_player, next_player, naught_list = [], cross_list = []):
self.naught_list = naught_list
self.cross_list = cross_list
self.empty_list = [1,2,3,4,5,6,7,8,9]
self.current_player = current_player
self.next_player = next_player
self.naught_trebles = []
self.naught_treble_sums = []
self.cross_trebles = []
self.cross_treble_sums = []
self.magic_dic = {1: 6,
2: 1,
3: 8,
4: 7,
5: 5,
6: 3,
7: 2,
8: 9,
9: 4}
def create_board(self):
gameDisplay.fill(BACKGROUND_COLOR)
drawGrid(DISPLAY_WIDTH, int(DISPLAY_WIDTH / BLOCK_SIZE), gameDisplay)
for i in range(9):
display_text(str(i+1), ((i)%3)*BLOCK_SIZE + BLOCK_SIZE/2.5, (i//3)*BLOCK_SIZE + BLOCK_SIZE/2.5, white)
def cover_text(self, square_num):
x = int((square_num%3)*BLOCK_SIZE + BLOCK_SIZE/2)
y = int((square_num//3)*BLOCK_SIZE + BLOCK_SIZE/2)
def play_move(self, marker, square_num, player):
if player.marker == 'naughts':
if int(square_num) in self.empty_list:
idx = square_num - 1 # user numbering starts at 1 but Python starts at 0
x = int((idx%3)*BLOCK_SIZE + BLOCK_SIZE/2)
y = int((idx//3)*BLOCK_SIZE + BLOCK_SIZE/2)
draw_rect(x, y)
draw_naught(x, y, player.color)
self.empty_list.remove(square_num)
self.naught_list.append(square_num)
tmp = player
self.current_player = self.next_player
self.next_player = tmp
else:
print("Invalid move - square already taken. Pick again please:")
return 0
elif player.marker == 'crosses':
if int(square_num) in self.empty_list:
idx = square_num - 1 # user numbering starts at 1 but Python starts at 0
x = int((idx%3)*BLOCK_SIZE + BLOCK_SIZE/2)
y = int((idx//3)*BLOCK_SIZE + BLOCK_SIZE/2)
draw_rect(x, y)
draw_cross(x, y, player.color)
self.empty_list.remove(square_num)
self.cross_list.append(square_num)
tmp = player
self.current_player = self.next_player
self.next_player = tmp
else:
print("Invalid move - square already taken. Pick again please:")
return 0
else:
print("Invalid marker for this player.")
def victory_line(self, winning_list, color, closed = False, thickness = 20):
# get the square numbers of the winning line. These will be in terms of magic square from magic_dic
magic_list_0 = winning_list[0]
magic_list_1 = winning_list[1]
magic_list_2 = winning_list[2]
# convert them back to the square numbers we see on the screen
for key in self.magic_dic:
if magic_list_0 == self.magic_dic[key]:
list_0 = key
for key in self.magic_dic:
if magic_list_1 == self.magic_dic[key]:
list_1 = key
for key in self.magic_dic:
if magic_list_2 == self.magic_dic[key]:
list_2 = key
non_magic_list = [list_0, list_1, list_2]
# subtract 1 as pygame numbers squares from 0 and we number from 1
left_idx = min(non_magic_list) - 1
right_idx = max(non_magic_list) -1
# get coords
left_x = int((left_idx%3)*BLOCK_SIZE + BLOCK_SIZE/2)
left_y = int((left_idx//3)*BLOCK_SIZE + BLOCK_SIZE/2)
right_x = int((right_idx%3)*BLOCK_SIZE + BLOCK_SIZE/2)
right_y = int((right_idx//3)*BLOCK_SIZE + BLOCK_SIZE/2)
# draw a line to show winning combination
pygame.draw.lines(gameDisplay, color, closed , [(left_x, left_y), (right_x, right_y)], thickness)
def magic_square_winner_check(self, player):
# magic square has every row, column and diagonal sum to 15 meaning we can just check if any triple of used squares sums to 15
# this won't be computationally challenging due to small board size. at most 5C3 = 10 combinations (no player can occupy more than 5 squares)
# current numbering is not magic so we must first use a dictionary to magic-ify the board
if player.marker == 'naughts':
updated_naught_list = [self.magic_dic[x] for x in self.naught_list]
self.naught_trebles = list(itertools.combinations(updated_naught_list, 3))
self.naught_treble_sums = [sum(x) for x in self.naught_trebles]
if 15 in self.naught_treble_sums:
print("Victory")
return 1
elif player.marker == 'crosses':
updated_cross_list = [self.magic_dic[x] for x in self.cross_list]
self.cross_trebles = list(itertools.combinations(updated_cross_list, 3))
self.cross_treble_sums = [sum(x) for x in self.cross_trebles]
if 15 in self.cross_treble_sums:
print("Victory")
return 1
else:
return 0
def victory_message(self, msg, x = DISPLAY_WIDTH//5, y=DISPLAY_HEIGHT+20, color = cyan):
text = largefont.render("{} wins!".format(str(msg)), True, color)
gameDisplay.blit(text, [x, y])
def draw_message(self, x = DISPLAY_WIDTH//6, y=DISPLAY_HEIGHT+20, color = cyan):
text = largefont.render("A boring draw...", True, color)
gameDisplay.blit(text, [x, y])
def player1_text(self, color, x = 10, y=DISPLAY_HEIGHT+30):
text = player_font.render("Player 1", True, color)
gameDisplay.blit(text, [x, y])
def player2_text(self, color, x = DISPLAY_WIDTH - 160, y= DISPLAY_HEIGHT+30):
text = player_font.render("Player 2", True, color)
gameDisplay.blit(text, [x, y])
class Player:
def __init__(self, marker, coin_toss_victor, color, name):
self.marker = marker # naughts or crosses
self.coin_toss_victor = coin_toss_victor #boolean indication of who starts
self.color = color
self.name = name
pass
def request_move(self, board):
move = input("Choose a square: ")
tmp = move
while move.isnumeric() == False:
move = input("{} is not an int! Choose again: ".format(tmp))
move = int(move)
# check valid
while move not in range(1,10):
tmp = move
move = int(input("{} is not a valid square. Please choose again: ".format(tmp)))
while move not in board.empty_list:
#board.square_taken_message()
tmp = move
move = int(input("Square {} is already taken. Please choose again: ".format(tmp)))
return move
"""<<<GAME LOOP>>>"""
def game_loop():
# display screen asking for coin fkip guess
gameDisplay.fill(BACKGROUND_COLOR)
myfont = pygame.font.SysFont('Comic Sans MS', 50)
textsurface = myfont.render("Heads or Tails?", True, white)
gameDisplay.blit(textsurface, [60, 10])
pygame.display.update()
# receive coin guess
coin = ["H", "T"]
coin_toss = input("We will decide who goes first with a coin flip. Player 1 pease enter H or T: ")
if coin_toss not in coin:
coin_toss = input("Not a valid input. Please enter H or T: ")
# dictionary for translating input to display words
coin_dic = {"H" : "Heads", "T": "Tails"}
# random toss. display the guess now. display the outcome after images
random_toss = random.choice(coin)
myfont = pygame.font.SysFont('Comic Sans MS', 50)
textsurface2 = myfont.render("Your choice: {}".format(coin_dic[coin_toss]), True, white)
gameDisplay.blit(textsurface2, [60, DISPLAY_HEIGHT - 140])
# load two images of coin
coin_a = pygame.image.load('coin_a.png')
coin_b = pygame.image.load('coin_b.png')
tosser = 0
textsurface3 = myfont.render("Result: {}".format(coin_dic[random_toss]), True, white)
if coin_toss == random_toss:
textsurface4 = myfont.render("Win! You go first!", True, white)
else:
textsurface4 = myfont.render("Lose! You go second!", True, white)
# change image 20 times for nice effect. display outcome of coin flip after 10 times.
while tosser < 21:
print(20 - tosser)
gameDisplay.blit(coin_a, (60,DISPLAY_HEIGHT//3))
pygame.display.update()
pygame.time.wait(100)
gameDisplay.blit(coin_b, (60, DISPLAY_HEIGHT//3))
pygame.display.update()
pygame.time.wait(100)
tosser += 1
if tosser > 10:
gameDisplay.blit(textsurface3, [60, DISPLAY_HEIGHT - 70])
gameDisplay.blit(textsurface4, [60, DISPLAY_HEIGHT])
pygame.display.update()
# short pause for user to read result before switching screen to tic-tac-toe
pygame.time.wait(500)
# instantiate the player objects according to the result of the coin toss
while coin_toss not in coin:
coin_toss = input("You didn't enter a valid input! Try again please: ")
if coin_toss == random_toss:
print("Coin toss result was {}".format(random_toss))
print("Player 1 to go first!")
p1 = Player('naughts', True, pink, 'Player 1')
p2 = Player('crosses', False, green, 'Player 2')
current_player = p1
next_player = p2
else:
print("Coin toss result was {}".format(random_toss))
print("Player 2 to go first!")
p1 = Player('naughts', False, pink, 'Player 1')
p2 = Player('crosses', True, green, 'Player 2')
current_player = p2
next_player = p1
# instantiate the board and display it
b = Board(current_player, next_player)
b.create_board()
# display current player
if current_player == p1:
b.player1_text(white)
b.player2_text(gray)
elif current_player == p2:
b.player1_text(gray)
b.player2_text(white)
pygame.display.update()
# begin while loop - initialise all variables here so they're reset if we restart the game
play_again = True
end = False
b.empty_list = [1,2,3,4,5,6,7,8,9]
b.naught_list = []
b.naught_trebles = []
b.naught_treble_sums = []
b.cross_list = []
b.cross_trebles = []
b.cross_treble_sums = []
while play_again:
# display current player
if current_player == p1:
b.player1_text(white)
b.player2_text(gray)
pygame.display.update()
elif current_player == p2:
b.player1_text(gray)
b.player2_text(white)
pygame.display.update()
# allow window to be quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
play_again = False
# print useful stuff to terminal
print("-----Empty Squares-----")
print(b.empty_list)
print("-----Naughts-----")
print(b.naught_list)
print(b.naught_trebles)
print(b.naught_treble_sums)
print("-----Crosses-----")
print(b.cross_list)
print(b.cross_trebles)
print(b.cross_treble_sums)
# request player move and display it
move = current_player.request_move(b)
b.play_move(current_player.marker, move, current_player)
# display current player
if current_player == p1:
b.player1_text(white)
b.player2_text(gray)
pygame.display.update()
elif current_player == p2:
b.player1_text(gray)
b.player2_text(white)
pygame.display.update()
# check if current player has won and then switch player
if current_player == p1 and end == False:
if b.magic_square_winner_check(p1) == 1:
draw_wide_rect(70, DISPLAY_HEIGHT+70)
draw_wide_rect(DISPLAY_WIDTH - 80, DISPLAY_HEIGHT+70)
b.victory_message(current_player.name)
winning_idx = b.naught_treble_sums.index(15)
winning_tuple = b.naught_trebles[winning_idx]
winning_list = [x for x in winning_tuple]
print(winning_list)
b.victory_line(winning_list, p1.color)
pygame.display.update()
end = True
else:
current_player = p2
elif current_player == p2 and end == False:
if b.magic_square_winner_check(p2) == 1:
draw_wide_rect(70, DISPLAY_HEIGHT+70)
draw_wide_rect(DISPLAY_WIDTH - 80, DISPLAY_HEIGHT+70)
b.victory_message(current_player.name)
winning_idx = b.cross_treble_sums.index(15)
winning_tuple = b.cross_trebles[winning_idx]
winning_list = [x for x in winning_tuple]
b.victory_line(winning_list, p2.color)
pygame.display.update()
end = True
else:
current_player = p1
# check if game is a draw
if len(b.empty_list) == 0 and end == False:
b.draw_message()
pygame.display.update()
end = True
# if game reaches a terminal state, return 1 (used as code in main loop to ask about restart)
if end:
return 1
pygame.display.update()
def main():
end_msg = game_loop()
while end_msg == True:
play_again = int(input("Play again? 1 = Yes, 0 = No : "))
if play_again == 1:
game_loop()
if play_again == 0:
break
if __name__ == '__main__':
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T11:22:05.293",
"Id": "211413",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"tic-tac-toe"
],
"Title": "Object Oriented Tic Tac Toe Python"
} | 211413 |
<p>I saw a programming puzzle. Find a string containing letters from a to z such that its MD5-hash starts like 314159265359. I am a junior programmer so I would like to know if I can solve the problem faster that checking firs strings a-z, then aa-zz, then aaa-zzz and so on. As the computation takes time, I save results to the file regularly to be able to continue computation. I put my Mint to autostart the application as desktop is on.</p>
<p>In particular, is there faster way to solve the problem and is there cleaner way to write the code:</p>
<pre><code>//using Datetime;
using System;
using System.IO;
using System.Text;
//using StringBuilder;
// This is an exercise from https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=ssana2 .
// It tries to find an md5-hash that begins with hexadecimals 314159265...
namespace RandomCS
{
public class Program
{
public static void Main()
{
DateTime dt1 = DateTime.Now;
Console.WriteLine(dt1);
string md5 = "";
string last = "a";
string c = "";
string file = "md5piresults.txt";
string path = "/home/jaakko/Desktop/Programming/";
int limit = 1;
int cp = 0;
string bestsa;
string charstring;
string[] lines = System.IO.File.ReadAllLines(@path+file);
Console.WriteLine(lines[0]+"\n" +lines[1]);
const string pi = "314159265358";
do {
last = lines[0].Substring(6,lines[0].Length-6);
Console.WriteLine("We got: "+last);
bestsa = lines[1].Substring(6,lines[1].Length-6);
charstring = last;
cp = CommonPrefix(CreateMD5(bestsa),pi).Length;
Console.WriteLine("The best we have found = "+bestsa+", md5="+CreateMD5(bestsa)+ ",n="+cp);
limit = cp+1;
TimeSpan aInterval = new System.TimeSpan(0, 0, 0, 3);
DateTime newTime = dt1.Add(aInterval);
while (!Console.KeyAvailable) {
// Console.WriteLine(DateTime.Now + " " + newTime+ DateTime.Compare(DateTime.Now, newTime));
if (DateTime.Compare(DateTime.Now, newTime) == 1)
{
// Console.WriteLine("Meni aikaa!");
newTime = DateTime.Now.Add(aInterval);
lines[0] = "last: " + charstring;
// lines[1] = "best: " + bestsa;
System.IO.File.WriteAllLines(@path + file, lines);
Console.WriteLine("We saved to the file " + file + " lines " + lines[0] + " and " + lines[1]);
}
md5 = CreateMD5(charstring);
c = CommonPrefix(md5,pi);
if (c.Length >= limit) {
Console.WriteLine(charstring+" " +md5+ " " +c.Length);
lines[0] = "last: "+charstring;
lines[1] = "best: "+charstring;
System.IO.File.WriteAllLines(@path +file,lines);
Console.WriteLine("We saved to the file " +file + " lines " + lines[0] + " and "+lines[1]);
limit = c.Length + 1;
}
charstring = Increase(charstring);
if (charstring == endstring(charstring.Length)) {
md5 = CreateMD5(charstring);
c = CommonPrefix(md5,pi);
if (c.Length >= limit) {
Console.WriteLine(charstring+" " +md5+ " "+c.Length);
lines[0] = "last: "+charstring;
lines[1] = "best: "+charstring;
System.IO.File.WriteAllLines(@path +file,lines);
limit = c.Length + 1;
}
charstring = startstring(charstring.Length+1);
}
}
}
while (Console.ReadKey(true).Key != ConsoleKey.Escape);
string best = "";
lines[0] = "last: "+charstring;
md5 = CreateMD5(charstring);
c = CommonPrefix(md5,pi);
if (c.Length >= limit) {
best = charstring;
lines[1] = "best: "+best;
}
System.IO.File.WriteAllLines(@path +file,lines);
Console.WriteLine("We exit at the point "+charstring);
Console.WriteLine(charstring);
Console.WriteLine(limit);
}
// This is from https://stackoverflow.com/questions/33709165/get-common-prefix-of-two-string .
public static string CommonPrefix(string a, string b)
{
if (a == null)
throw new ArgumentNullException(nameof(a));
if (b == null)
throw new ArgumentNullException(nameof(b));
var min = Math.Min(a.Length, b.Length);
var sb = new StringBuilder(min);
for (int i = 0; i < min && a[i] == b[i]; i++)
sb.Append(a[i]);
return sb.ToString();
}
private static string startstring(int n) {
string start = "";
for (int i=0; i<n; ++i) {
start += "a";
}
return start;
}
private static string endstring(int n) {
string end = "";
for (int i=0; i<n; ++i) {
end += "z";
}
return end;
}
// This is from https://stackoverflow.com/questions/11454004/calculate-a-md5-hash-from-a-string
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
// The idea is from https://artofproblemsolving.com/community/c163h1699980_how_to_find_the_next_string_in_c
private static string Increase(string thing)
{
char[] charArray = thing.ToCharArray();
bool differentcharacter = false;
for (int i=0; i<charArray.Length; ++i) {
if (charArray[i]!= 'z') {
differentcharacter = true;
}
}
if (differentcharacter == false) {
return thing;
}
bool carry = false;
for (int i = charArray.Length - 1; i >= 0; i--)
{
char c = charArray[i];
if (carry)
{
if (c != 'z' && c != 'Z')
{
charArray[i] = ++c;
break;
}
charArray[i] = (char) (c - 25);
} else
{
if (c != 'z' && c != 'Z')
{
charArray[i] = (char) (c + 1);
break;
}
charArray[i] = (char) (c - 25);
carry = true;
}
}
return new String(charArray);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T15:03:22.350",
"Id": "408803",
"Score": "4",
"body": "Maybe give it another clean-up pass before asking for feedback. There's debugging code, commented-out lines, inconsistent formatting, and poor variable names before we get to the meat. You'll get more useful feedback if you submit your best effort."
}
] | [
{
"body": "<p>MD-5 is a cryptographic hash-function, it was designed so that it is hard to find an input which produces a particular output.</p>\n\n<p>So it's unlikely you will find an approach better than \"brute force\".</p>\n\n<p>That said, MD-5 is known to have cryptographic weaknesses, so it's not out of the question to find a faster method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:41:20.767",
"Id": "409357",
"Score": "0",
"body": "So what you are saying is that it's difficult, but then again maybe not so difficult? So what are you saying here exactly?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T00:55:47.680",
"Id": "211589",
"ParentId": "211415",
"Score": "1"
}
},
{
"body": "<p>If I understand things correctly, then what you're trying to do is called a 'preimage attack'. That's a lot harder than 'just' finding a hash collision. Apparently there is a known preimage attack for MD5, but it's only slightly better than a brute-force approach, so I don't think that'll be of any practical use here.</p>\n\n<p>But the challenge you're referring to is more of a 'who can find the longest matching prefix', so it's about how efficient your code is and how patient you are.</p>\n\n<hr>\n\n<p>Regarding efficiency, there are a few things you can do to speed it up:</p>\n\n<ul>\n<li>You're creating a new <code>MD5</code> instance every time you want to generate an MD5 hash. Don't do that - create a single instance when your program starts and keep using that until the program ends.</li>\n<li>You're constantly converting between strings and byte arrays. That involves a lot of extra work and extra allocations, which will slow things down. Use byte arrays everywhere, and modify them in-place whenever possible.</li>\n</ul>\n\n<hr>\n\n<p>Other things you can do that will make the code easier to understand and maintain:</p>\n\n<ul>\n<li>Code duplication: both file-writing and hash comparing are duplicated several times. Each of these only needs to occur once in the code.</li>\n<li><code>Main</code> contains two nested loops and quite a few additional checks. A single loop should be sufficient, and its body only needs to check a hash, update the longest-match if necessary, 'increase' the input and check if it's time to write the current state to a file.</li>\n<li>Declaring local variables up-front, instead of as close to where they are used as possible, tends to make code more difficult to understand. I think the main reason why you'll sometimes see this style is because it used to be required in certain older languages.</li>\n<li>Type names like <code>System.IO.File</code>, <code>System.TimeSpan</code>, <code>System.Security.Cryptography.MD5</code> and so on can be simplified to <code>File</code>, <code>TimeSpan</code> and <code>MD5</code> thanks to <code>using <namespace>;</code> statements.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T11:08:06.493",
"Id": "211613",
"ParentId": "211415",
"Score": "1"
}
},
{
"body": "<p>The basics:</p>\n\n<ul>\n<li><p>Use consistent indenting. Your editor can help if you want to move a block out a level, as in <code>CreateMD5</code>.</p></li>\n<li><p>Completed code shouldn't have commented out lines. If you want to leave something in for debugging, either use the built-in <code>Debug</code> class or write your own function which can be disabled with a flag.</p></li>\n<li><p>Your variable names are not good. <code>dt1</code> could be <code>startTime</code>, <code>cp</code> could be <code>lengthToBeat</code>, <code>c</code> could be <code>commonPrefix</code>. Good variable names make your code self-documenting.</p></li>\n<li><p>Most of your code is in a single function, with just a few static helpers. The IO code should be moved out into other functions. You could move the string incrementation to a separate class.</p></li>\n</ul>\n\n<p>In terms of optimization, the biggest win would be to use more than a single core on your machine. You would have to know what you are doing, but it will give you an immediate 4x speedup if you avoid contention. An added benefit is that this will force you to organize your code better. In terms of smaller improvements, the key is going to avoid doing unnecessary work. Look at <code>CommonPrefix</code>: you build up a string, but when you are done all you use is its length. If all you want is to count characters that match, you can have it return an int.</p>\n\n<p>Similarly, if you think about this problem some more, it doesn't actually require you to convert the hash to a hex string. Given a byte array, you can easily count how many bytes match your target string. If you want it to start \"31\" then the first byte has to be <code>0x31</code>. So full bytes (2 hex chars) are easy, and the only challenge is to handle single chars.</p>\n\n<p>Another possible speedup would be to avoid the allocations and conversions involved in your string increment and hashing. Since your strings are all ASCII anyway, you could work directly with a <code>byte[]</code>, increment it in place, and pass it straight to the hashing function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-22T02:58:23.077",
"Id": "211961",
"ParentId": "211415",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T11:53:17.870",
"Id": "211415",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"hashcode"
],
"Title": "Find MD5-hash whose hexadecimals starts like digits of π"
} | 211415 |
<p>I am learning Python for a few weeks. Last time I started object-oriented programming and I feel like it is really hard for me to write the relation between methods and attributes for different objects. </p>
<p>I tried to write simpler version BlackJack card game only with Hit or Stand option. </p>
<p>Could you have a look at my code and possibly give me some advice what I should change or improve?</p>
<pre><code>import random
SUITS = ['Heart','Diamond','Club','Pike']
FIGURES = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
MONEY = 200
MIN_BET = 2
class Card:
'''
Single card class
Use it in loop to make full french deck of card
print return 'Figure of suit'
'''
def __init__(self,suit,figure):
self.suit = suit
self.figure = figure
if self.figure == "A":
self.value = 11
elif self.figure in ['J','Q','K']:
self.value = 10
else:
self.value = int(self.figure)
def __str__(self):
return f'{self.figure} of {self.suit}'
def __repr__(self):
return f'{self.figure} of {self.suit}'
class Deck:
def __init__(self):
self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]
def shuffle(self):
random.shuffle(self.deck)
def draw(self):
return self.deck.pop(0)
def restart(self):
self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self, card):
self.cards.append(card)
self.check_aces()
def check_value(self):
'''
Change self.value
Doesnt return any value
'''
ace = self.aces
self.value = 0
for i in range(len(self.cards)):
self.value += self.cards[i].value
while self.value > 21 and ace > 0:
self.value -= 10
ace -= 1
if self.value > 21:
self.isBusted = True
return self.value
def check_aces(self):
'''
Check if 'A' in Hand
'''
self.aces = 0
for i in range(len(self.cards)):
if self.cards[i].figure == 'A':
self.aces += 1
# I know i should make new class dealer inherit from Hand with this function
def dealer_ai(self,d):
self.check_value()
while self.value < 17:
self.add_card(d.draw())
self.check_value()
print(f'Dealer cards: {self.cards} ')
def restart(self):
self.cards = []
self.value = 0
self.aces = 0
class Bank:
def __init__(self, money, min_bet):
self.money = money
self.min_bet = min_bet
self.play = True
self.pool = 0
self.check_money()
print(self)
def __str__(self):
return f'You have {self.money}$'
def check_money(self):
if self.money < self.min_bet:
self.play = False
else:
self.play = True
def bet(self):
print(f'You have {self.money}$.')
while True:
try:
bet = int(input('Tell me your bet (should be lower or equal then your money)'))
except:
continue
else:
break
if bet>self.money:
self.bet()
else:
self.pool = 2*bet
self.money -= bet
print(f'Your new balance: {self.money}$')
def deposite(self,depo):
self.money += depo
def player_win(self):
self.deposite(self.pool)
print(f'You won: {self.pool}$ \nYour new balance is {self.money}.')
self.pool = 0
def player_lose(self):
print(f'Sorry! You lose {self.pool/2}.\nYour new balance is {self.money}')
self.pool = 0
def play_choice():
choice = ''
while True:
choice = input('Do you want to play? Y or N: ')
if choice.lower() == "y":
return True
elif choice.lower() == 'n':
return False
else:
play_choice()
def main():
print('Welcome in Blackjack game! There is only two options - hit or stand')
print('If you dont know rules - google for Blackjack')
##Creating Objects
deck = Deck()
player_hand = Hand()
dealer_hand = Hand()
bank = Bank(MONEY,MIN_BET)
winner = True
is_playing = play_choice()
##1 round -> Draw, hit/stand -> dealer -> check if win
while is_playing:
while True:
deck.restart()
player_hand.restart()
dealer_hand.restart()
deck.shuffle()
bank.bet()
#Lets draw 4 cards - 2 For you, 2 for Dealer
player_hand.add_card(deck.draw())
player_hand.add_card(deck.draw())
dealer_hand.add_card(deck.draw())
dealer_hand.add_card(deck.draw())
player_hand.check_value()
print(f'\n\nYour cards: {player_hand.cards} with {player_hand.value} value')
print(f'Dealer first card: {dealer_hand.cards[0]} ')
choice = input('\n\nWhats your choice? - "h" for hit / "s" for stand')
while choice.lower() == 'h':
player_hand.add_card(deck.draw())
player_hand.check_value()
print(f'\n\nYour cards: {player_hand.cards} with {player_hand.value} value')
if player_hand.value >= 21:
break
choice = input('\n\nWhats your choice? - "h" for hit / "s" for stand')
###
## Check for player value
if player_hand.value == 21:
winner = True
break
elif player_hand.value > 21:
winner = False
break
dealer_hand.dealer_ai(deck)
if dealer_hand.value > 21:
winner = True
break
elif dealer_hand.value == 21:
winner = False
break
elif player_hand.value > dealer_hand.value:
winner = True
break
else:
winner = False
break
if winner:
bank.player_win()
else:
bank.player_lose()
is_playing = play_choice()
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<p><strong>Confusing documentation and lack of consistency</strong></p>\n\n<pre><code>def check_value(self):\n '''\n Change self.value\n Doesnt return any value\n '''\n ace = self.aces\n self.value = 0\n\n for i in range(len(self.cards)):\n self.value += self.cards[i].value\n\n while self.value > 21 and ace > 0:\n self.value -= 10\n ace -= 1\n\n if self.value > 21:\n self.isBusted = True\n\n return self.value\n\ndef check_aces(self):\n '''\n Check if 'A' in Hand \n '''\n self.aces = 0\n\n for i in range(len(self.cards)):\n if self.cards[i].figure == 'A':\n self.aces += 1\n</code></pre>\n\n<p>In <code>check value</code> you say \"Doesn't return any value\" but it clerly has a return statement inside. It is important that code and comments never contradict each other. In your code you do not use the return value as far as I can see so this is confusing</p>\n\n<p>In <code>check_aces</code> instead no value is returned but the name is very similar to the function above where something is returned.</p>\n\n<p>You should try to keep consistent language between your methods.</p>\n\n<p><strong>Built-in count and list comprehension</strong></p>\n\n<p>You say <code>Check if 'A' in Hand</code> but you do not use the <code>in</code> keyword!</p>\n\n<p>This way is much simpler:</p>\n\n<pre><code>figures = [card.figure for card in self.cards]\nself.aces = figures.count('A')\n</code></pre>\n\n<p><strong><code>restart</code></strong></p>\n\n<p>Conceptually I feel like </p>\n\n<pre><code>def restart(self):\n self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]\n</code></pre>\n\n<p>should shuffle the deck, you cannot restart with all the cards in order.</p>\n\n<p><strong>\"Native\" iteration</strong></p>\n\n<pre><code> for i in range(len(self.cards)):\n self.value += self.cards[i].value\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>for card in self.cards:\n self.value += card.value\n</code></pre>\n\n<p>Much cleaner.</p>\n\n<p>This page is good to learn python built-in methods for clean looping <a href=\"https://www.datadependence.com/2016/02/pythonic-for-loops/\" rel=\"noreferrer\">https://www.datadependence.com/2016/02/pythonic-for-loops/</a></p>\n\n<p><strong>Potential debug problems</strong></p>\n\n<pre><code> while True:\n try:\n bet = int(input('Tell me your bet (should be lower or equal then your money)'))\n except:\n continue\n</code></pre>\n\n<p>Always specify which exception to except otherwise this suppresses all kinds of errors and can make debugging inconvenient.</p>\n\n<p><strong>minor</strong></p>\n\n<pre><code>def check_money(self):\n self.play = self.money > self.min_bet\n</code></pre>\n\n<p><strong>Good</strong></p>\n\n<p>I see you separated logic and input/output handling, this is very good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T21:11:22.637",
"Id": "230339",
"ParentId": "211418",
"Score": "6"
}
},
{
"body": "<h1>Bugs</h1>\n\n<ul>\n<li><strong>Do you want to play?</strong> infinite loop after pressing a wrong key, the program keeps printing the same prompt over and over no matter what the input is.</li>\n<li><strong>Negative inputs:</strong> The program accepts negative monetary values and adds them to your current wealth if you lost.</li>\n</ul>\n\n<h1>Style</h1>\n\n<p>I suggest you check <strong>PEP0008</strong> <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide when writing your code and <strong>Flake8</strong> <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">http://flake8.pycqa.org/en/latest/</a> as a tool for style enforcement and the following goes accordingly:</p>\n\n<ul>\n<li><p><strong>Missing whitespace after a comma:</strong> </p>\n\n<pre><code>SUITS = ['Heart','Diamond','Club','Pike']\nFIGURES = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']\ndef __init__(self,suit,figure):\nelif self.figure in ['J','Q','K']:\n</code></pre>\n\n<p><strong>are written:</strong></p>\n\n<pre><code>SUITS = ['Heart', 'Diamond', 'Club', 'Pike']\nFIGURES = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\ndef __init__(self, suit, figure):\nelif self.figure in ['J', 'Q', 'K']:\n</code></pre></li>\n<li><p><strong>Docstrings:</strong></p>\n\n<pre><code>'''\nSingle card class\nUse it in loop to make full french deck of card\nprint return 'Figure of suit'\n'''\n</code></pre>\n\n<p><strong>Python documentation strings</strong> (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It's specified in source code that is used, like a comment, to document a specific segment of code and are usually accessed using <code>help()</code> They should describe what the classes/functions do instead of how and are delimited by triple double quotes.\nMost of your defined methods do not contain docstrings while they should.</p>\n\n<p>The docstring above should be enclosed in triple double quotes and should contain a description of what the class does not how:</p>\n\n<pre><code>\"\"\"\nBuild a french deck of cards.\n\"\"\"\n</code></pre></li>\n<li><p><strong>Blank lines</strong>: Surround top-level function and class definitions with two blank lines.Method definitions inside a class are surrounded by a single blank line.Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).</p>\n\n<p><strong>Examples:</strong></p>\n\n<p><strong>2 lines should be left between these:</strong></p>\n\n<pre><code>MIN_BET = 2\n\nclass Card:\n</code></pre>\n\n<p><strong>And these:</strong></p>\n\n<pre><code>self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]\n\nclass Hand:\n</code></pre>\n\n<p>And too many blank lines are left in your <code>main()</code> function.</p></li>\n<li><p><strong>Bare except:</strong> You should be indicating the type of exception likely to occur (ex: IndexError, TypeError ...) instead of the too broad exception clause.</p></li>\n<li><p><strong>Typo:</strong> <code>def deposite():</code> is <code>def deposit():</code></p></li>\n<li><p><strong>Comments:</strong> start with a single <code>#</code> and a capital letter and end with <code>.</code></p>\n\n<p><code>##Creating Objects</code> is written <code># Creating objects.</code></p>\n\n<p><strong>and</strong></p>\n\n<p><code>##1 round -> Draw, hit/stand -> dealer -> check if win</code></p>\n\n<p><strong>is written:</strong></p>\n\n<p><code># 1 round -> Draw, hit/stand -> dealer -> check if win.</code>\nand same goes for all other comments</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><p><strong>Global variables:</strong> are bad in Python and all programming languages, the reason behind them being bad that they might produce some very hard to trace side effects and lead something called 'Spaghetti Code'. I suggest you enclose them inside their respective functions/methods that use them or you might even make them class variables (if that's necessary).</p></li>\n<li><p><strong>inefficient <code>pop()</code>:</strong>\nIn your <code>Deck</code> class:</p>\n\n<pre><code>def draw(self):\nreturn self.deck.pop(0)\n</code></pre>\n\n<p>when you're popping the first element of a list there will be n - 1 rearrangements of the remaining items in the list which is inefficient for large lists(not the case here). And since the deck will be shuffled so only return <code>self.deck.pop()</code> is sufficient.</p></li>\n<li><p><strong>Instance attributes defined outside constructor:</strong>\nIn your <code>check_value()</code> method: </p>\n\n<pre><code>if self.value > 21:\n self.isBusted = True\n</code></pre>\n\n<p>instance attributes should be defined inside the constructor <code>__init__()</code> only.</p></li>\n<li><p><strong>Magic numbers:</strong> </p>\n\n<pre><code>self.value = 11\nself.value = 10\nwhile self.value > 21 and ace > 0:\nself.value -= 10\nwhile self.value < 17:\nself.pool = 0\n</code></pre>\n\n<p>These numbers should be function parameters or have some commented explanations provided.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T21:13:04.937",
"Id": "230340",
"ParentId": "211418",
"Score": "6"
}
},
{
"body": "<p>Looks like a pretty good start. Your Deck and Card classes are basically fine, aside from perhaps a few docstrings. I should be telling you to really add them, and it's definitely better practice, but on the other hand they're clear and readable enough that you can do without them.</p>\n\n<p>Only minor details is those you could keep rename <code>shuffle</code> to <code>_shuffle</code> and call it everytime in <code>__init__</code> and <code>restart</code>, but that's just different code, not neccesarily better. It's advantage would be that you can't forget to call it. </p>\n\n<h2>Hand</h2>\n\n<h3>Hand.check_aces()</h3>\n\n<p>Why is there a <code>check_aces()</code> method? You use it only once. In fact, I daresay you could make the check a simple one-liner with a <a href=\"https://docs.python.org/3/reference/expressions.html#generator-expressions\" rel=\"noreferrer\">generator expression</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def check_aces(self):\n return sum(card.figure == \"A\" for card in self.cards) \n</code></pre>\n\n<p>This checks all the cards in <code>self.cards</code>, and returns a boolean <code>True</code> for each ace. Since the boolean True has an integer value of 1, you can sum them to count the aces.</p>\n\n<p>You could easily inline it like that one-liner, but we'll leave it as a function for now, for the sake of clarity.</p>\n\n<p>Do please note that I return the value instead of just calculating and storing it. Bear with me for a moment, you'll see why.</p>\n\n<h3>Hand.check_value()</h3>\n\n<p>Your docstring is wrong, you do return a value. And that's generally a good thing. However, given that you never use it, it might be all-right in this case. For the chase of perfection, however, you could make this a cached calculation instead, which is slightly easier to use then what you do now, but without calculating it more than required. This would look something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def __init__(self):\n self._value = 0 # Note the rename\n self.cards = []\n\n @property\n def value(self):\n if not self._value: # Same as \"is zero\"\n aces = check_aces() \n # This is the only place we actually use the number of aces. That makes it better to \n # just return it instead of using two lines - one to calculate and one to retrieve.\n value = sum(card.value for card in self.cards)\n # Generator expression in a sum again. Most simple loops can be replaced this way.\n if aces > 1:\n value -= (aces - 1) * 10\n self._value = value\n return self._value\n</code></pre>\n\n<p>If you aren't familiar with <code>@property</code>, here are <a href=\"https://docs.python.org/3/howto/descriptor.html\" rel=\"noreferrer\">the docs</a></p>\n\n<p>This will first check if the saved value is zero. If so, it will calculate the value, then return it. And this is all done the moment someone else types <code>hand.value()</code>. But if it is not zero, then it recalculates it.</p>\n\n<p>Do note that I removed the <code>isBroken</code> variable. You never used it.</p>\n\n<p>Normally in cache tracking you'd have a different variable as a flag to see if you need to refresh your cache, instead of a magic value that we use here. Or they use timestamps. However, this is small enough in scope that I think a magic variable isn't harmful. Do note, however, that you need to signal this recalculation every time the hand value changes, therefore:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def add_card(self, card):\n self.cards.append(card)\n self._value = 0\n\ndef restart(self):\n self.cards = []\n self._value = 0\n</code></pre>\n\n<h3>Hand.dealer_ai()</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code> def dealer_ai(self,d):\n while self.value < 17:\n self.add_card(d.draw())\n print(f'Dealer cards: {self.cards} ')\n</code></pre>\n\n<p>Due to the check_value refactoring we did by shoving it into a property, note that we can just remove 2 different calls to that function here, making it that much easier to read. However, this function really does two things - it acts on it's state, which is very appropriate to the function name, and it prints it. That's a lot less appropriate. You should also return this value, or just leave it and reach into the class and retrieve Hand.cards from outside when you want to use this.</p>\n\n<h2>Bank</h2>\n\n<h3>Back.check_money()</h3>\n\n<p>Same as the check_value, really. Make it a property, like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> @property\n def play(self):\n return self.money < self.min_bet\n</code></pre>\n\n<p>I'd cache here to, but comparing two integers is so check that no caching will ever be an advantage. Do note that the \"<\" comparison operator, along with all other operators you generally use in an <code>if (expression):</code> block, already return boolean values. Therefore you can return it directly. The only exceptions are the <code>or</code> and <code>and</code> operators, which will return the last evaluated value instead. (which has it's own uses I won't go into now.)</p>\n\n<h3>Bank.bet()</h3>\n\n<p>This really should be a method that takes an integer. It should not check input values. And it should certainly not recurse on invalid values. The print()s here also should really be handled by retrieval from outside. </p>\n\n<p>You also forgot to check for your value being bigger than <code>min_bet</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def bet(self, value):\n \"\"\" Bets money. Assumes there are valid bets possible. \"\"\"\n if self.min_bet <= value <= self.money:\n self.pool = 2*bet\n self.money -= bet\n return True # Tell the caller the Bank is ok with this bet.\n return False # Tell the caller the bet is rejected.\n</code></pre>\n\n<p>If you want input validation, you can write a function for that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_integer(request_message):\n while True:\n try:\n return int(input(request_message))\n except ValueError:\n continue\n</code></pre>\n\n<p>And then use it like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>value = 0\nwhile bank.play: # Checks if there are valid bets\n value = get_integer(\"Tell me your bet (should be lower or equal then your money)\")\n if bank.bet(value):\n break\n else:\n print(f\"Sorry, {value} is not a valid bet. It has to be between {bank.min_bet} and {bank.money}.\")\n</code></pre>\n\n<h3>Bank.player_[win/lose]</h3>\n\n<p>Again, move the prints out. Looks good for the rest.</p>\n\n<h3>main</h3>\n\n<p>You can drop the entire <code>while True:</code> loop. You never <code>continue</code>, only break, and with that last if-statement, you always break the first iteration.</p>\n\n<p>If you follow the <code>@property</code> recommendations above, you can of course drop all check_value() statements in the loop, so I won't explicitly point them out. Instead I'll silently drop them.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> choice = input('\\n\\nWhats your choice? - \"h\" for hit / \"s\" for stand')\n while choice.lower() == 'h':\n player_hand.add_card(deck.draw())\n print(f'\\n\\nYour cards: {player_hand.cards} with {player_hand.value} value')\n if player_hand.value >= 21:\n break\n choice = input('\\n\\nWhats your choice? - \"h\" for hit / \"s\" for stand')\n</code></pre>\n\n<p>You're duplicating the <code>input()</code> function call here. Better do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> while 'h' == input('\\n\\nWhats your choice? - \"h\" for hit / \"s\" for stand').lower().strip():\n player_hand.add_card(deck.draw())\n print(f'\\n\\nYour cards: {player_hand.cards} with {player_hand.value} value')\n if player_hand.value >= 21:\n break\n</code></pre>\n\n<p>Which is shorter and more readable. Readability is also the reason I switched the \"h\" and the input call - you can see what happens even if you don't read the entire line.</p>\n\n<h3>Victory Check</h3>\n\n<p>I would just call the functions directly, instead of grabbing a manual variable.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> if player_hand.value == 21:\n bank.player_win()\n elif player_hand.value > 21:\n bank.player_lose()\n</code></pre>\n\n<p>And of course the same with the others. Note that the removal of the <code>while True:</code> loop also allows us to skip all those break statements, at the low cost of changing all <code>if</code>s that aren't the first to <code>elif</code>s instead. Alternatively, you can structure it like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> dealer_hand.dealer_ai(deck)\n if player_hand.value == 21 or dealer_hand > 21 or player_hand.value > dealer_hand.value:\n bank.player_win()\n else:\n bank.player_lose()\n</code></pre>\n\n<p>(Note: It took me a while to write, and there are 2 new answers since I started... I haven't checked them, though.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T21:37:01.190",
"Id": "230342",
"ParentId": "211418",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T12:51:01.900",
"Id": "211418",
"Score": "10",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented",
"playing-cards"
],
"Title": "Simpler version of BlackJack game - first OOP"
} | 211418 |
<p>In the absence of feature-complete and easy-to-use <a href="https://en.wikipedia.org/wiki/One-hot" rel="nofollow noreferrer">one-hot encoders</a> in the Python ecosystem I've made a set of my own. This is intended to be a small library, so I want to make sure it's as clear and well thought out as possible.</p>
<p>I've implemented things from a <a href="https://codereview.stackexchange.com/questions/201011/simple-one-hot-encoder">previous question</a> concerning only the base encoder, but also expanded it to two separate use cases. Also, let me know if this is not a place for such lengthy code and I'll narrow it down.</p>
<p>I would especially like to know if this is publishable code. So any criticism, on functionality, style or anything is greatly appreciated. Make it harsh too.</p>
<pre><code>import numpy as np
import pandas as pd
class ProgrammingError(Exception):
"""
Error caused by incorrect use or sequence of routines.
"""
class OneHotEncoder:
"""
Simple one-hot encoder.
Does not handle unseen categories: will default to the first category.
Does not invert all-zero arrays: will default to the first category.
Does not handle NaN data.
Example:
>>> oh = OneHotEncoder()
>>> oh.fit(np.array(['a', 'b', 'c', 'd']))
>>> oh.transform(np.array(['a', 'c', 'd', 'a']))
>>> oh.inverse(np.array([[0, 1, 0, 0]]))
"""
def __init__(self):
self._categories = None
@property
def categories(self) -> np.ndarray:
if self._categories is None:
raise ProgrammingError('Encoder not fitted!')
return self._categories
@categories.setter
def categories(self, categories) -> None:
self._categories = categories
@property
def n_categories(self) -> int:
return len(self.categories)
def __repr__(self):
return 'OneHotEncoder with categories:\n' + str(self.categories)
def fit(self, samples: np.ndarray) -> 'OneHotEncoder':
"""
Fit the encoder with the unique elements in categories.
:param samples: np.ndarray
:return: None
"""
self.categories = np.unique(samples)
return self
def transform(self, samples: np.ndarray) -> np.ndarray:
"""
Transform samples into their one-hot encoding.
:param samples: np.ndarray
:return: encoding
"""
return self.transform_from_labels(self.transform_to_labels(samples))
def transform_to_labels(self, samples: np.ndarray) -> np.ndarray:
"""
Transform samples to labels (numericals).
:param samples: np.ndarray
:return: labels
"""
arr = np.argwhere(self.categories == samples.reshape(-1, 1))
labels = np.zeros((samples.size,), dtype=int)
labels[arr[:, 0]] = arr[:, 1]
return labels.reshape(samples.shape)
def transform_from_labels(self, labels: np.ndarray) -> np.ndarray:
"""
Transform labels to one-hot encoding.
:param labels: np.ndarray
:return: encoding
"""
return np.eye(self.n_categories)[labels]
def inverse_from_labels(self, labels: np.ndarray) -> np.ndarray:
"""
Invert labels to original categories.
:param labels: np.ndarray
:return: categories
"""
return self.categories[labels]
@staticmethod
def inverse_to_labels(encoded: np.ndarray) -> np.ndarray:
"""
Invert one-hot encoding to label values
:param encoded: np.ndarray
:return: labels
"""
return np.argmax(encoded, axis=-1)
def inverse(self, encoded: np.ndarray) -> np.ndarray:
"""
Invert one-hot encoding to original categories.
:param encoded: np.ndarray
:return: categories
"""
return self.inverse_from_labels(self.inverse_to_labels(encoded))
def _mask_assign(shape: tuple, mask: np.ndarray, values: np.ndarray, init: float=np.nan) -> np.ndarray:
array = np.full(shape, init)
array[mask] = values
return array
class NanHotEncoder(OneHotEncoder):
"""
One-hot encoder that handles NaN values. Uses pd.isnull to find NaNs.
Does handle NaN data, ignores unseen categories (all zero) and inverts all zero rows.
Only accepts and returns 1-dimensional data (pd.Series) as samples (categories).
Example:
>>> nh = NanHotEncoder()
>>> nh.fit(np.array(['a', 'b', 'c', 'd']))
>>> nh.transform(pd.Series([np.nan, 'c', 'd', 'a']))
>>> nh.inverse(np.array([[0, 0, 0, 0], [0, 0, 1, 0]]))
"""
def __init__(self):
super().__init__()
def __repr__(self):
return 'Nan' + super().__repr__()[3:]
def fit(self, samples: np.ndarray) -> 'NanHotEncoder':
super().fit(samples[~pd.isnull(samples)])
return self
def transform_from_labels(self, labels: np.ndarray) -> np.ndarray:
nans = np.isnan(labels)
encoded = super().transform_from_labels(labels[~nans].astype(int))
return _mask_assign(labels.shape + (self.n_categories,), ~nans, encoded, init=0)
def inverse_to_lables(self, encoded: np.ndarray) -> np.ndarray:
nans = np.sum(encoded, axis=-1) == 0
inverted = super().inverse_to_labels(encoded[~nans].astype(int))
return _mask_assign(encoded.shape[:-1], ~nans, inverted)
def transform_to_labels(self, samples: pd.Series) -> np.ndarray:
mask = samples.isnull() | ~samples.isin(self.categories)
labels = super().transform_to_labels(samples[~mask].values)
return _mask_assign(samples.values.shape, ~mask.values, labels)
def inverse_from_labels(self, labels: np.ndarray) -> pd.Series:
series = pd.Series(labels.ravel())
inverted = super().inverse_from_labels(series.dropna().values.astype(int))
series[~series.isnull()] = inverted
return series
def transform(self, samples: pd.Series) -> np.ndarray:
return self.transform_from_labels(self.transform_to_labels(samples))
def inverse(self, encoded: np.ndarray) -> pd.Series:
return self.inverse_from_labels(self.inverse_to_labels(encoded))
class CatHotEncoder(OneHotEncoder):
"""
One-hot encoder that handles NaN values built around Pandas Categorical type and conventions.
Does handle NaN data, ignores unseen categories (all zero) and inverts all zero rows.
Only accepts and returns 1-dimensional data (pd.Series) as samples (categories).
Example:
>>> s = pd.Series(pd.Categorical([np.nan, 'c', 'd', 'a', 'b', 'c', 'c']))
>>> ch = CatHotEncoder()
>>> ch.fit(s)
>>> ch.transform(s)
>>> ch.inverse(np.array([[0, 0, 0, 0], [0, 0, 1, 0]]))
"""
def __init__(self):
super().__init__()
def __repr__(self):
return 'Cat' + super().__repr__()[3:]
def fit(self, samples: pd.Series) -> 'CatHotEncoder':
super().fit(samples.cat.categories)
return self
def transform_from_labels(self, labels: np.ndarray) -> np.ndarray:
nans = (labels == -1)
encoded = super().transform_from_labels(labels[~nans].astype(int))
return _mask_assign(labels.shape + (self.n_categories,), ~nans, encoded, init=0)
def inverse_to_lables(self, encoded: np.ndarray) -> np.ndarray:
nans = np.sum(encoded, axis=-1) == 0
inverted = super().inverse_to_labels(encoded[~nans].astype(int))
return _mask_assign(encoded.shape[:-1], ~nans, inverted, init=-1)
def transform_to_labels(self, samples: pd.Series) -> np.ndarray:
raise ProgrammingError('Redundant action for pd.Categorical. Use series.cat.codes instead.')
def inverse_from_labels(self, labels: np.ndarray) -> pd.Series:
raise ProgrammingError('Redundant action for pd.Categorical. Use pd.Categorical.from_codes instead.')
def transform(self, samples: pd.Series) -> np.ndarray:
return self.transform_from_labels(samples.cat.set_categories(self.categories).cat.codes)
def inverse(self, encoded: np.ndarray) -> pd.Series:
codes = self.inverse_to_labels(encoded)
return pd.Series(pd.Categorical.from_codes(codes, self.categories))
</code></pre>
<p>To test it out, please find the examples in each classes docstring or this test suite. Tests are also up for judgement!</p>
<pre><code>import unittest
def array_equal(a: np.ndarray, b: np.ndarray) -> np.ndarray:
return (a == b) | ((a != a) & (b != b))
class TestOneHotEncoder(unittest.TestCase):
str_categories = np.array(['a', 'b', 'c', 'd'])
def setUp(self):
self.oh = OneHotEncoder().fit(self.str_categories)
def test_fit(self):
self.assertTrue(np.all(self.str_categories == self.oh.categories))
def test_transform_to_labels(self):
samples = np.array([[['a', 'c'], ['b', 'c']], [['d', 'd'], ['a', 'd']]])
result = np.array([[[0, 2], [1, 2]], [[3, 3], [0, 3]]])
self.assertTrue(np.all(self.oh.transform_to_labels(samples) == result))
def test_transform_from_labels(self):
labels = np.array([[0, 2], [1, 3]])
result = np.array([[[1, 0, 0, 0], [0, 0, 1, 0]], [[0, 1, 0, 0], [0, 0, 0, 1]]])
self.assertTrue(np.all(self.oh.transform_from_labels(labels) == result))
def test_inverse_from_labels(self):
labels = np.array([[[0, 2], [1, 2]], [[3, 3], [0, 3]]])
result = np.array([[['a', 'c'], ['b', 'c']], [['d', 'd'], ['a', 'd']]])
self.assertTrue(np.all(self.oh.inverse_from_labels(labels) == result))
def test_inverse_to_labels(self):
encoded = np.array([[[1, 0, 0, 0], [0, 0, 1, 0]], [[0, 1, 0, 0], [0, 0, 0, 1]]])
result = np.array([[0, 2], [1, 3]])
self.assertTrue(np.all(self.oh.inverse_to_labels(encoded) == result))
class TestNanHotEncoder(unittest.TestCase):
categories = np.array(['a', 'b', 'c', 'd', np.nan, np.nan], dtype=object)
def setUp(self):
self.nh = NanHotEncoder().fit(self.categories)
def test_fit(self):
self.assertTrue(np.all(array_equal(self.nh.categories, self.categories[:-2])))
def test_transform_to_labels(self):
samples = pd.Series(['a', 'c', np.nan, 'c', 'd', np.nan, 'a', 'd'])
result = np.array([0, 2, np.nan, 2, 3, np.nan, 0, 3])
self.assertTrue(np.all(array_equal(self.nh.transform_to_labels(samples), result)))
def test_transform_from_labels(self):
labels = np.array([[0, np.nan], [np.nan, 3]])
result = np.array([[[1, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 1]]])
self.assertTrue(np.all(array_equal(self.nh.transform_from_labels(labels), result)))
def test_inverse_from_labels(self):
labels = np.array([0, 2, np.nan, 2, 3, np.nan, 0, 3])
result = pd.Series(['a', 'c', np.nan, 'c', 'd', np.nan, 'a', 'd'])
self.assertTrue(self.nh.inverse_from_labels(labels).equals(result))
def test_inverse_to_labels(self):
encoded = np.array([[[1, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 1]]])
result = np.array([[0, np.nan], [np.nan, 3]])
self.assertTrue(np.all(array_equal(self.nh.inverse_to_lables(encoded), result)))
def test_novel_classes(self):
samples = pd.Series(['a', 'f', np.nan, 'd'])
result = np.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]])
self.assertTrue(np.all(array_equal(self.nh.transform(samples), result)))
class TestCatHotEncoder(unittest.TestCase):
series = pd.Series(pd.Categorical([np.nan, 'c', 'd', 'a', 'b', 'c', 'c']))
def setUp(self):
self.ch = CatHotEncoder().fit(self.series)
def test_transform_to_labels(self):
with self.assertRaises(ProgrammingError):
self.ch.transform_to_labels(self.series)
def test_transform_from_labels(self):
labels = np.array([[0, -1], [-1, 3]])
result = np.array([[[1, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 1]]])
self.assertTrue(np.all(array_equal(self.ch.transform_from_labels(labels), result)))
def test_inverse_from_labels(self):
with self.assertRaises(ProgrammingError):
self.ch.transform_to_labels(self.series)
def test_inverse_to_labels(self):
encoded = np.array([[[1, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 1]]])
result = np.array([[0, -1], [-1, 3]])
self.assertTrue(np.all(array_equal(self.ch.inverse_to_lables(encoded), result)))
def test_novel_classes(self):
samples = pd.Series(pd.Categorical(['a', 'f', np.nan, 'd']))
result = np.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]])
self.assertTrue(np.all(array_equal(self.ch.transform(samples), result)))
if __name__ == '__main__':
oh_test = TestOneHotEncoder()
nh_test = TestNanHotEncoder()
ch_test = TestCatHotEncoder()
test = unittest.TestSuite()
test.addTests([oh_test, nh_test, ch_test])
res = unittest.TestResult()
test.run(res)
</code></pre>
| [] | [
{
"body": "<p>Some improvement's I've come up with myself:</p>\n\n<ul>\n<li>Change <code>__repr__</code> of child classes to not use the parent, slicing the string seems a bit confusing.</li>\n<li>Return <code>pd.DataFrame</code> from child classes with categories as headers for easy use afterwards.</li>\n<li>Actually check for the one-dimensionality in <code>transform_from_labels</code> of child classes that was required in docstring but now also enforced by returning a DataFrame.</li>\n<li>Change test suite accordingly, namely get <code>.values</code> of the DF for tests and pass 1D data.</li>\n</ul>\n\n<p>I may be blind to other mistakes so I still very much welcome other answers!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:41:12.657",
"Id": "211625",
"ParentId": "211419",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T14:42:52.990",
"Id": "211419",
"Score": "4",
"Tags": [
"python",
"numpy",
"pandas",
"machine-learning"
],
"Title": "Set of one-hot encoders in Python"
} | 211419 |
<p>I have used Stacks to check for brackets mismatch. (Parentheses matching problem using Stack algorithm)</p>
<p>Any suggestions on how to improve the code? </p>
<p>I have tried various examples and it works without error but I feel there is a lack of specificity. How do I work on that? </p>
<p>Side note: I think there's a stack reference type in Java but I am not allowed to use that. </p>
<pre><code>import java.util.Scanner;
class ParensMatching
{
static Character Stack[]= new Character[25];
static int ptr = -1;
static void push(char ch)
{
if(ptr+1 < 25)
{
Stack[++ptr]= ch;
}
else
{
System.out.println("Overflow!! ");
}
}
static int pop()
{
if (ptr == -1)
{
System.out.println("Underflow!!");
return 999;
}
int value = Stack[ptr];
ptr = ptr-1;
return value;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter a string");
String str = sc.nextLine();
char temp;
int i = 0;
outer:
for (i = 0; i< str.length(); i++)
{
if(str.charAt(i)== '('|| str.charAt(i)== '{' || str.charAt(i)== '[')
{
push(str.charAt(i));
temp = str.charAt(i);
}
else if(str.charAt(i)== ')')
{
if(pop()!= '(')
{
System.out.println("Unmathced parens, exitting! ");
break outer;
}
}
else if(str.charAt(i)== '}')
{
if(pop()!= '{')
{
System.out.println("Unmathced parens, exitting! ");
break outer;
}
}
else if(str.charAt(i)== ']')
{
if(pop()!= '[')
{
System.out.println("Unmathced parens, exitting! ");
break outer;
}
}
}
if(ptr != -1)
{
System.out.println("Missing closing parens!!");
}
else if (i == str.length())
{
System.out.println("Success. No unmatched parens");
}
System.out.println("Enter 2 to stop testing");
int n = sc.nextInt();
if(n == 2)
break;
else
continue;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T16:41:17.390",
"Id": "408811",
"Score": "1",
"body": "Why the downvote?"
}
] | [
{
"body": "<p>Make a separate stack class. Even if this is a one time thing it is good OO practice. Good encapsulation will not allow the main program to access the stack's internal structure, <code>ptr</code> for example. Methods like <code>Stack.isEmpty()</code> would be more user friendly. If popping "below the bottom" of the stack, it's better returning <code>null</code> rather than a specific out of range ptr value. I think the stack should be self-expanding, but if intentional design says it is fixed length then fine.</p>\n<p>Design classes with excellent customer service built in.</p>\n<hr />\n<pre><code>if (ptr == -1)\n</code></pre>\n<p>I suggest <code>ptr <= -1</code>. This is really the condition and it is more error tolerant. What if some other bug decremented to -2 before this check?</p>\n<hr />\n<p>Data structures to simplify code</p>\n<p>We want to avoid this:</p>\n<pre><code>if(str.charAt(i)== '('|| str.charAt(i)== '{' || str.charAt(i)== '[')\n</code></pre>\n<p>Not extensible, error prone, hard to read. The goal is something like this:</p>\n<pre><code>if( OpenDelimiters.contains ( str.charAt(i) ) )\n</code></pre>\n<p>There might be <code>OpenDelimiters</code>, <code>CloseDelimiters</code>, <code>PairDelimiter</code> structures - that might seem like a lot but code gets real simple real fast as seen above. Adding delimiters means no code changes, just add to the data structures.</p>\n<hr />\n<p><strong>Edit - RE: <code>if(ptr == -1)</code></strong></p>\n<p>This needs clarification. Please be patient, this is a case of something simple taking extensive explanation to show how and why it is wrong.</p>\n<p>The big picture is this:</p>\n<ul>\n<li>code the algorithm as precisely as possible</li>\n<li>Don't assume simple code is bug free</li>\n<li>Even correct arithmetic, at the bits and bytes level can be surprisingly inaccurate.</li>\n<li>Make code robust because ongoing maintenance is toxic to code.</li>\n<li>Develop good coding techniques that reduce bug risk and apply them consistently</li>\n</ul>\n<hr />\n<p><strong>Algorithm vis-a-vis Code</strong></p>\n<p>Pretend the program calculated <code>ptr = -2</code> instead of <code>-1</code>. Then <code>if(ptr == -1)</code> does not catch it. What is the error, the arithmetic or the condition or both? Change the condition to <code>if(ptr == -2)</code> and the program is fixed, right? How about we just throw an exception, is the program fixed now? If it runs why not?</p>\n<ul>\n<li>When <code>pop()</code>ing we need to catch "going off the bottom" of the stack. <em>By definition</em> that means an index less than zero. That algorithm definition is accurately coded as <code>ptr < 0</code>.\n<ul>\n<li>Given the above, if ptr is <code>-2</code> - this is not a program error per se. The program will keep running correctly. The <code>pop</code> algorithm handles that condition - index is less than zero.</li>\n<li>if <code>ptr</code> is <code>-2</code> - now this must be coding error because we intended <code>-1</code>. Lucky we're testing for <code>< 0</code>. Fix the arithmetic bug even if the conditional statement tolerates it. The arithmetic error and the conditional logic are two separate things. Arithmetic errors should be caught in testing. P.S.: throwing exceptions for arithmetic errors is just wrong!!</li>\n<li><code>if(ptr == -1)</code> is not an execution bug but it is wrong. The algorithm is not coded correctly. There is no arithmetic error yet code change has more potential for inducing execution bugs. The program will fail if the value is anything except <code>-1</code>.</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p><strong>Bit-level numbers</strong></p>\n<p>Testing for exact values can bite you. It just became easier for me to quit testing for exactly -1 than to try to out smart the compiler or interpreter or my inadvertent bugs-waiting-to-happen or the idiot maintenance programmer (sometimes that was me).</p>\n<p>Binary numbers in memory have inherent problems just like base-10 does. 1/3 in base-10 is .333... to infinity. Sometimes numbers converted to binary are like that.</p>\n<p>Sometimes computation induces errors. For example the sum of a taylor series added "forward" can - will - be different from adding "backwards". I.E. 1/2 + 1/3 + 1/4 + 1/5 ...... Do this for many thousand of terms and you'll see.</p>\n<p>Even integer arithmetic can be quirky in some languages. JavaScript, for example, does not have integers. All numbers are stored as floating point in memory. Google "javascript the weird parts" and you'll see funky numeric WTFs.</p>\n<p><strong>end Edit</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T04:48:29.860",
"Id": "408859",
"Score": "0",
"body": "*What if some other bug decremented to -2 before this check?*\n\nI don't understand how it could automatically change to -2. Which bug would cause that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T06:29:42.410",
"Id": "408861",
"Score": "0",
"body": "The code is checking for an index out of bounds condition. Well, out of bounds is not only -1. Everything below -1 is also out of bounds. So check for \"equal to or less than.\" In fact everything below zero is out of bounds. So check for either ` < 0` or `<= -1`. Next, *\"how could it ... change to -2\"* That's what bugs do, cause errors. I did not say there was a bug in that specific code but limit/error checking should cover the error potential range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T06:44:45.153",
"Id": "408862",
"Score": "1",
"body": ".... continued... Always put error trapping where ever possible. Put a final \"else\" on if/else, a \"default\" on switch statements, cover the range of potential computational error as in this case, etc. Good error checking is integral to quality code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:47:44.597",
"Id": "409008",
"Score": "0",
"body": "@radarbob good error checking is good, unnecessary error checking like the `<=-1` makes code more complicated, and **might obfuscate the real error**, making it harder to detect. If you really want to code defensively here, check for `==-1` for regular flow. Throw an `IllegalStateException` if it is `<-1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:49:35.910",
"Id": "409009",
"Score": "0",
"body": "Also, the `OpenDelimiters` variable does not adhere to the Java naming conventions. It should start with a lowercase."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T19:12:12.120",
"Id": "211430",
"ParentId": "211424",
"Score": "1"
}
},
{
"body": "<h2>Java naming conventions</h2>\n\n<p>Please follow the <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">Java naming conventions</a>. Variables should start with a lowercase character, so it should read (also note the placing of <code>[]</code> makes it clearer that stack is an array of <code>Character</code>)</p>\n\n<pre><code>static Character[] stack= new Character[25]; \n</code></pre>\n\n<h2>Why maximum stack size?</h2>\n\n<p>There is no given requirement for the limit of the size of the stack, so you should not use a fixed-size data structure like array, but rather opt for something like <code>List</code></p>\n\n<pre><code> static List<Character> stack= new ArrayList<>(); \n</code></pre>\n\n<h2>Separation of concerns</h2>\n\n<p>There are two functionalities in you code directly interwoven. First, there is the 'Stack', then there is the usage of the <code>Stack</code>. Move all the <code>Stack</code> related functionality to its own class.</p>\n\n<h2>Don't use magic values</h2>\n\n<p>If there is an error in the state of the stack (for example, if you try to <code>pop()</code> an empty stack, you could throw an <code>Exception</code>, for example a <code>NoSuchElementException()</code>. Or you can have the Stack of Optional and return <code>Optional.empty()</code>. Or even return <code>null</code> if no empty values on the stack are allowed.</p>\n\n<p>See for example the question <a href=\"https://codereview.stackexchange.com/q/171862/21279\">here</a>. Also check the answers. </p>\n\n<h2>Pair the parentheses, separate to own data type</h2>\n\n<p>You could implement a Delimiter enum type, like such:</p>\n\n<pre><code>enum Delimiter\n{\n PARENTHESES( '(', ')' ),\n BRACES ( '{', '}' ),\n BRACKETS ( '[', ']' );\n //easily expandable with for example: 〔 〕 – tortoise shell brackets\n\n\n public final char openChar;\n public final char closeChar;\n\n public Delimiter(char openChar, char closeChar)\n {\n this.openChar = openChar;\n this.closeChar = closeChar;\n }\n}\n</code></pre>\n\n<p>Then, when looping over the characters, you could use:</p>\n\n<pre><code> for (i = 0; i< str.length(); i++)\n {\n char c = str.charAt(i);\n for (Delimiter delimiter : Delimiter.values())\n {\n if (c == delimiter.openChar)\n {\n stack.push(delimiter);\n } \n else if (c == delimiter.closeChar)\n {\n //pop the stack and check if the closechar matches the openchar of the popped element\n\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:02:48.000",
"Id": "211525",
"ParentId": "211424",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T16:28:08.803",
"Id": "211424",
"Score": "2",
"Tags": [
"java",
"stack",
"balanced-delimiters"
],
"Title": "Using the stack algorithm for parenthesis matching"
} | 211424 |
<p>I have comma-delimited files like these, where the first field is sorted in increasing order:</p>
<h3>Case 1 ( 1st file ) :</h3>
<pre><code>abcd,1
abcd,21
abcd,122
abce,12
abcf,13
abcf,21
</code></pre>
<h3>Case 2 ( and another file like this ) :</h3>
<pre><code>abcd,1
abcd,21
abcd,122
</code></pre>
<p>What I want to do is convert the first file to like this : </p>
<pre><code>abcd 1,21,122
abce 12
abcf 13,21
</code></pre>
<p>And similarly, for the second file like this :</p>
<pre><code>abcd 1,21,122
</code></pre>
<p>Now, I wrote a very ugly code with a lot of if's to check whether the next line's string before the comma is same as current line's string so, if it is then do ....</p>
<p>It's so badly written that, I wrote it myself around 6 months back and it took me around 3-4 minutes to understand why I did what I did in this code.
Well in short it's ugly, in case you would like to see, here it is ( also there's a bug currently in here and since I needed a better way than this whole code so I didn't sort it out, for the curious folks out there the bug is that it doesn't print anything for the second case mentioned above and I know why ).</p>
<pre><code>def clean_file(filePath, destination):
f = open(filePath, 'r')
data = f.read()
f.close()
curr_string = current_number = next_string = next_number = ""
current_numbers = ""
final_payload = ""
lines = data.split('\n')[:-1]
for i in range(len(lines)-1):
print(lines[i])
curr_line = lines[i]
next_line = lines[i+1]
curr_string, current_number = curr_line.split(',')
next_string, next_number = next_line.split(',')
if curr_string == next_string:
current_numbers += current_number + ","
else:
current_numbers += current_number # check to avoid ',' in the end
final_payload += curr_string + " " + current_numbers + "\n"
current_numbers = ""
print(final_payload)
# For last line
if curr_string != next_string:
# Directly add it to the final_payload
final_payload += next_line + "\n"
else:
# Remove the newline, add a comma and then finally add a newline
final_payload = final_payload[:-1] + ","+next_number+"\n"
with open(destination, 'a') as f:
f.write(final_payload)
</code></pre>
<p>Any better solutions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T19:02:18.880",
"Id": "408819",
"Score": "4",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<ol>\n<li>To solve the grouping problem, use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>.</li>\n<li>To read files with comma-separated fields, use the <a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\"><code>csv</code></a> module.</li>\n<li><p>In almost all cases, <code>open()</code> should be called using a <code>with</code> block, so that the files will be automatically closed for you, even if an exception occurs within the block:</p>\n\n<pre><code>with open(file_path) as in_f, open(destination, 'w') as out_f:\n data = csv.reader(in_f)\n # code goes here\n</code></pre></li>\n<li><code>filePath</code> violates <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">Python's official style guide</a>, which recommends underscores, like your <code>curr_line</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T18:00:33.643",
"Id": "211427",
"ParentId": "211425",
"Score": "6"
}
},
{
"body": "<p>While @200_success's answer is very good (always use libraries that solve your problem), I'm going to give an answer that illustrates how to think about more general problems in case there isn't a perfect library.</p>\n\n<h3>Use <code>with</code> to automatically close files when you're done</h3>\n\n<p>You risk leaving a file open if an exception is raised and <code>file.close()</code> is never called.</p>\n\n<pre><code>with open(input_file) as in_file:\n</code></pre>\n\n<h3>Use the object to iterate, not indices</h3>\n\n<p>Most collections and objects can be iterated over directly, so you don't need indices</p>\n\n<pre><code>with open(input_file) as in_file:\n for line in in_file:\n line = line.strip() # get rid of '\\n' at end of line\n</code></pre>\n\n<h3>Use data structures to organize your data</h3>\n\n<p>In the end, you want to associate a letter-string with a list of numbers. In python, a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\" rel=\"nofollow noreferrer\"><code>dict</code></a> allows you to associate any piece of data with any other, so we'll use that to associate the letter-strings with a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#more-on-lists\" rel=\"nofollow noreferrer\"><code>list</code></a> of numbers.</p>\n\n<pre><code>with open(input_file) as in_file:\n data = dict()\n for line in in_file:\n line = line.strip() # get rid of '\\n' at end of line\n letters, numbers = line.split(',')\n data[letters].append(numbers)\n</code></pre>\n\n<p>Now, this doesn't quite work since, if a <code>letters</code> entry hasn't been seen yet, the call to <code>data[letters]</code> won't have anything to return and will raise a <code>KeyError</code> exception. So, we have to account for that</p>\n\n<pre><code>with open(input_file) as in_file:\n data = dict()\n for line in in_file:\n line = line.strip() # get rid of '\\n' at end of line\n letters, number = line.split(',')\n try: # there might be an error\n data[letters].append(number) # append new number if letters has been seen before\n except KeyError:\n data[letters] = [number] # create new list with one number for a new letter-string\n</code></pre>\n\n<p>Now, all of the file is stored in a convenient form in the <code>data</code> object. To output, just loop through the <code>data</code></p>\n\n<pre><code>with open(input_file) as in_file:\n data = dict()\n for line in in_file:\n line = line.strip() # get rid of '\\n' at end of line\n letters, number = line.split(',')\n try: # there might be an error\n data[letters].append(number) # append new number if letters has been seen before\n except KeyError:\n data[letters] = [number] # create new list with one number for a new letter-string\n\nwith open(output_file, 'w') as out_file:\n for letters, number_list in data.items(): # iterate over all entries\n out_file.write(letters + ' ' + ','.join(number_list) + '\\n')\n</code></pre>\n\n<p>The <code>.join()</code> method creates a string from a list such that the entries of the list are separated by the string that precedes it--<code>','</code> in this case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T23:04:10.793",
"Id": "408837",
"Score": "1",
"body": "Instead of trying to append and catching the error, you can use [`setdefault`](https://docs.python.org/3/library/stdtypes.html#dict.setdefault): `data.setdefault(letters, []).append(number)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T23:08:36.343",
"Id": "408840",
"Score": "0",
"body": "@ToddSewell Neat! That'll be useful in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T14:24:11.503",
"Id": "408907",
"Score": "0",
"body": "Or use `collections.defaultdict` of course."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T22:47:16.310",
"Id": "211442",
"ParentId": "211425",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211427",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T17:31:37.893",
"Id": "211425",
"Score": "7",
"Tags": [
"python",
"csv"
],
"Title": "Grouping comma-separated lines together"
} | 211425 |
<p>I am currently developing a Unity-based multiplatform game (PC, iOS, Android) in a small team. This is the code we have created for the character actions inside the game. I am looking for feedback on the code itself as well as tips on how some Unity features could be used better. This is my first time developing a game with Unity.</p>
<p>The game is also aimed for mobile platforms as stated above, so tips on optimization are welcome.</p>
<pre><code>using AI.Enemy;
using UnityEngine;
namespace Player.Script.Miru
{
public class MiruScript : MonoBehaviour
{
public float Health;
public float MoveSpeed;
public float JumpHeight;
public float EvadeSpeed;
public float DefendCooldownTimer;
public float NormalDamage;
public float Cooldown;
public float Stamina;
public float HealthRegenerationRate;
public float StaminaRegenerationRate;
private bool _IsFacingForward;
private bool _IsGrounded;
private Rigidbody2D _RigidBody;
private RaycastHit2D _GroundDetector;
private RaycastHit2D _RightRayCast;
private RaycastHit2D _LeftRayCast;
private MinionScript _MinionScript;
private void Start() //Temporary values
{
MoveSpeed = 4f * Time.deltaTime;
JumpHeight = 10f;
EvadeSpeed = 5f;
DefendCooldownTimer = 0f;
NormalDamage = 50f;
Cooldown = 1f;
Stamina = 100f;
Health = 100f;
HealthRegenerationRate = 0.5f;
StaminaRegenerationRate = 10f;
_RigidBody = GetComponent<Rigidbody2D>();
_MinionScript = GetComponent<MinionScript>();
}
private void Update()
{
MoveRight(MoveSpeed);
MoveLeft(MoveSpeed);
Jump(JumpHeight);
Evade(EvadeSpeed);
Attack(NormalDamage);
DistanceFromObject();
AttackCooldown();
Defend();
}
private bool AttackCooldown()
{
if (Cooldown < 1f)
{
Cooldown += Time.deltaTime;
return true;
}
return false;
}
public int DamageDealt(float _damageDealt)
{
Health -= _damageDealt;
if (Health <= 0)
Destroy(gameObject);
return 0;
}
private int DistanceFromObject()
{
_RightRayCast = Physics2D.Raycast(transform.position, Vector2.right);
_LeftRayCast = Physics2D.Raycast(transform.position, Vector2.left);
if (_RightRayCast.distance < 1.5f && _LeftRayCast.distance < 1.5f)
return 3;
if (_RightRayCast.distance < 1.5f)
return 1;
if (_LeftRayCast.distance < 1.5f)
return 2;
return 0;
}
private int Attack(float _damageDealt)
{
if (_IsFacingForward && Input.GetKeyDown(KeyCode.X) && _RightRayCast.distance <= 1.5f && !AttackCooldown())
{
_MinionScript = _RightRayCast.collider.gameObject.GetComponent<MinionScript>();
_MinionScript.DamageDealt(_damageDealt);
Cooldown = 0;
return 1;
}
if (_IsFacingForward == false && Input.GetKeyDown(KeyCode.X) && _LeftRayCast.distance <= 1.5f && !AttackCooldown())
{
_MinionScript = _LeftRayCast.collider.gameObject.GetComponent<MinionScript>();
_MinionScript.DamageDealt(_damageDealt);
Cooldown = 0;
return 2;
}
return 0;
}
private int MoveRight(float _moveSpeed)
{
if (Input.GetKey(KeyCode.RightArrow) && Defend() == 0)
{
transform.Translate(_moveSpeed, 0, 0);
_IsFacingForward = true;
return 1;
}
return 0;
}
private int MoveLeft(float _moveSpeed)
{
if (Input.GetKey(KeyCode.LeftArrow) && Defend() == 0)
{
transform.Translate(-_moveSpeed, 0, 0);
_IsFacingForward = false;
return 1;
}
return 0;
}
private int Jump(float _height)
{
_GroundDetector = Physics2D.Raycast(transform.position, Vector2.down);
if (Input.GetKeyDown(KeyCode.Z) && _IsGrounded)
{
_RigidBody.AddForce(Vector2.up * _height, ForceMode2D.Impulse);
return 1;
}
if (_GroundDetector.distance > 0.6f)
{
_IsGrounded = false;
return 2;
}
_IsGrounded = true;
return 0;
}
private int Evade(float _evadeSpeed)
{
if (Input.GetKeyDown(KeyCode.Space) && _IsGrounded)
switch (DistanceFromObject())
{
case 1:
_RigidBody.AddForce(Vector2.up * _evadeSpeed, ForceMode2D.Impulse);
_RigidBody.AddForce(Vector2.left * _evadeSpeed, ForceMode2D.Impulse);
return 1;
case 2:
_RigidBody.AddForce(Vector2.up * _evadeSpeed, ForceMode2D.Impulse);
_RigidBody.AddForce(Vector2.right * _evadeSpeed, ForceMode2D.Impulse);
return 2;
case 3:
_RigidBody.AddForce(Vector2.up * _evadeSpeed * 3, ForceMode2D.Impulse);
return 3;
}
return 0;
}
private int Defend()
{
if (Input.GetKey(KeyCode.Space) && _IsGrounded)
{
DefendCooldownTimer += Time.deltaTime;
if (DefendCooldownTimer >= 0.5f)
{
return 1;
}
}
else
DefendCooldownTimer = 0f;
return 0;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Magic numbers like 0, 1, 2 and 3 returned by <code>DistanceFromObject</code> are difficult to read and are easily mixed up. Use an <code>enum</code> instead.</p>\n\n<pre><code>[Flags]\nprivate enum Proximity\n{\n None = 0,\n Right = 1,\n Left = 2,\n LeftAndRight = Left | Right\n}\n\n// A constant allows you to change the value easily.\nprivate const float ProximityLimit = 1.5f;\n\nprivate Proximity DistanceFromObject()\n{\n _RightRayCast = Physics2D.Raycast(transform.position, Vector2.right);\n _LeftRayCast = Physics2D.Raycast(transform.position, Vector2.left);\n\n if (_RightRayCast.distance < ProximityLimit && _LeftRayCast.distance < ProximityLimit)\n return Proximity.LeftAndRight;\n\n if (_RightRayCast.distance < ProximityLimit)\n return Proximity.Right;\n\n if (_LeftRayCast.distance < ProximityLimit)\n return Proximity.Left;\n\n return Proximity.None;\n}\n</code></pre>\n\n<p>The <code>Evade</code> method becomes easier to read.</p>\n\n<pre><code>private Proximity Evade(float _evadeSpeed)\n{\n if (Input.GetKeyDown(KeyCode.Space) && _IsGrounded) {\n Proximity proximity = DistanceFromObject();\n switch (proximity) {\n case Proximity.Right:\n _RigidBody.AddForce(Vector2.up * _evadeSpeed, ForceMode2D.Impulse);\n _RigidBody.AddForce(Vector2.left * _evadeSpeed, ForceMode2D.Impulse);\n break;\n\n case Proximity.Left:\n _RigidBody.AddForce(Vector2.up * _evadeSpeed, ForceMode2D.Impulse);\n _RigidBody.AddForce(Vector2.right * _evadeSpeed, ForceMode2D.Impulse);\n break;\n\n case Proximity.LeftAndRight:\n _RigidBody.AddForce(Vector2.up * _evadeSpeed * 3, ForceMode2D.Impulse);\n break;\n }\n return proximity;\n }\n\n return Proximity.None;\n}\n</code></pre>\n\n<p>Corresponding refactorings can be applied to <code>Attack</code> and <code>Jump</code></p>\n\n<p>In places where Unity requires you to use an <code>int</code> (I'm not a Unity developer), at least use constants.</p>\n\n<pre><code>const int NoProximity = 0, RightProximity = 1, ...;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T00:54:50.830",
"Id": "408848",
"Score": "0",
"body": "Special thumbs-up for defining `Proximity.None`. For enums generally always do this. Then enum variables must be explicitly set, reducing potential bugs from \"blindly set\" to valid but possibly wrong values. Consider a switch `default`. First as a general principle but also this can help catch errors when adding new enums and/or extensive editing, especially with \"large\" enums. It would not be the first time a \"cannot ever happen\" error had been caught."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T20:03:53.490",
"Id": "211433",
"ParentId": "211428",
"Score": "3"
}
},
{
"body": "<p>Disclaimer: I'm not a Unity coder so this is C#-focused feedback, Unity might change some things or have different conventions. Apologies if I cause confusion as a result.</p>\n\n<p><strong>Prefer properties over fields</strong> and <strong>prefer encapsulation</strong> (i.e avoid public setters), for example <code>public float Health { get; private set; }</code>. Currently, any other code in your game can set the <code>Health</code> to whatever it wants, when it should be calling DamageDealt() and letting the object work out its own health!</p>\n\n<p>The private method <code>Start()</code> appears not to be called at all, though perhaps Unity works some reflection magic to call it? In any case, <strong>prefer inline initialization</strong>, for example <code>private Rigidbody2D _RigidBody = GetComponent<Rigidbody2D>();</code>. This may not always be appropriate (e.g. if members need different starting values depending how they are constructed) but used properly means the object can immediately be in a valid state as soon as it is created.</p>\n\n<p><strong>Avoid \"magic numbers\"</strong> - another answer has already mentioned enums over ints, but the same applies for other constants. For example <code>private const float MaxHealth = 100f;</code> then later <code>Health = MaxHealth;</code> gives more meaning to what's going on. It also means that if the same value is used in multiple places (such as the repeated appearance of 1.5f in <code>DistanceFromObject</code> and <code>Attack</code>) and you later decide it needs to change, you only need to change it in one place if you have <code>private const float CheckDistance = 1.5f;</code> - otherwise, can you guarantee you wouldn't miss changing it somewhere? Finally, it gives you the flexibility in future to change constants to variables - perhaps you decide your game has Easy/Normal/Hard difficulty levels, you could make <code>MaxHealth</code> a static variable and change how much health the player starts with, for example.</p>\n\n<p>Personally I'd put <code>MoveRight()</code> and <code>MoveLeft()</code> into a single <code>Move()</code> method. It'd be a bit clearer that way, and would mean <code>Defend</code> need only be called once, and the result stored. (It's currently possible for it to be called by both methods, so the <code>DefendCooldownTimer</code> will be incremented twice if left arrow, right arrow, and space are all pressed. Is that intentional?) In fact I wonder if it might be appropriate for all the code that checks input to be in the same method, because it checks for different key presses in different places at the moment and that's not very clear. However, there's a danger that approach could end up with a giant method that tries to do everything, which would be just as bad (and which you currently avoid).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T10:25:23.610",
"Id": "409474",
"Score": "0",
"body": "The Start() method is called automatically by Unity upon initialization. Some unity classes, methods and others can only be called inside Start()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T10:31:22.173",
"Id": "409475",
"Score": "0",
"body": "OK, fair enough, I wondered if that might be the case. That being the case, initialise inline when you can, or in Start() when you have to."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T09:25:59.363",
"Id": "211755",
"ParentId": "211428",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T19:09:36.307",
"Id": "211428",
"Score": "2",
"Tags": [
"c#",
"unity3d"
],
"Title": "Class for handling player movement and / or similar behaviour"
} | 211428 |
<p>I just recently began going over number systems again, granted I didn't pay very much attention to it the first time for lack of understanding its importance (I've only been coding for a year and some change). Below this paragraph of text I have a simple Binary to Decimal converter, and I was wondering if there's a better way to do this, or if my algorithm is okay:</p>
<pre><code>import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String Binary = scan1.next(); // 11011
double power = 0;
double sum = 0;
for (int i = Binary.length() - 1; i >= 0; i--) {
char TempHold = Binary.charAt(i);
double num = Character.getNumericValue(TempHold);
sum = (sum + (num * (Math.pow(2, power))));
power++;
}
System.out.println(sum + "(10)");
}
}
</code></pre>
<p>My process: </p>
<ol>
<li>The first step was to, of course, allow the user to input their own binary number for testing purposes with a scanner and a variable of String called <em>Binary</em> for the initialization of this input (I chose to make this a String vs an Integer for looping purposes).</li>
<li><p>Next I created a variable of type double called <em>power</em> that will start off at 0 and be utilized in the for loop later.</p></li>
<li><p>Lastly, as far as preliminary variable declarations go, I created a <em>sum</em> variable to hold the sum of the binary-decimal conversion.</p></li>
<li><p>Within the for loop I ensured that my iterator traversed the String backwards in respect to my method of conversion.</p></li>
<li><p>After setting up the for loop, I created a variable of type Character called <em>TempHold</em> to seize and store the character of the <em>Binary</em> variable that corresponds to the current iteration of the loop.</p></li>
<li><p>My next step was to parse the <em>TempHold</em> Character variable into a String so that I could utilize it arithmetically in my conversion method.</p></li>
<li><p>At the end of this for loop I incremented the <em>power</em> variable so that I could increase the value of the exponent being used in the conversion method. </p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:03:52.077",
"Id": "408863",
"Score": "0",
"body": "While your code is a nice example for learning the principles and received a nice review by Ralf, do not forget that the java base library contains solutions for most everyday problems. In this case, have a look at `Integer.parseInt(String s, int radix)` for parsing and `Integer.toBinaryString(int i)` for output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T10:59:34.317",
"Id": "409022",
"Score": "0",
"body": "Thanks, I didn't know that! :)"
}
] | [
{
"body": "<p>Your algorithm is ok, there are only a few minor hints for improvement:</p>\n\n<p>You're using <code>double</code>-typed variables. Although in your case the computations will be exact up to fairly large numbers, it's generally safer to use <code>int</code> or <code>long</code> if you don't need the fractional part.</p>\n\n<p>Two of your variable names begin with an upper-case letter (<code>Binary</code> and <code>TempHold</code>). That's unusual for Java code, as the vast majority of programs follows the naming conventions, so much that I find it irritating to read non-conforming code.</p>\n\n<p>Your variable <code>power</code> has a name that confused me first. I'd call it <code>exponent</code> (in mathematics, \"power\" is the result of exponentiation). And I'd rename <code>TempHold</code> to <code>digitChar</code> and <code>num</code> to <code>digitVal</code>.</p>\n\n<p><code>Math.pow()</code> isn't really fast, so I recommend a different approach. With every iteration, the power grows by a factor of two, so I'd use something like <code>power = power * 2;</code> inside the loop.</p>\n\n<p>For production code, you should separate input/output from computation, e.g. by putting the conversion part into a method of its own.</p>\n\n<p>It's good style to close Scanners when they are finished (although that will eventually be done by Java's garbage collector if you don't do it explicitly).</p>\n\n<p>So, my version of your program would be:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class BinaryToDecimal {\n\n public static void main(String[] args) {\n Scanner scan1 = new Scanner(System.in);\n System.out.println(\"Enter a binary number: \");\n String binary = scan1.next(); // 11011\n\n String decimal = toDecimal(binary);\n\n System.out.println(decimal + \"(10)\");\n scan1.close();\n }\n\n public static String toDecimal(String binary) {\n long power = 1;\n long sum = 0;\n\n for (int i = binary.length() - 1; i >= 0; i--) {\n char digitChar = binary.charAt(i);\n int digitVal = Character.getNumericValue(digitChar);\n sum = sum + digitVal * power;\n power = power * 2;\n }\n return String.valueOf(sum);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T22:00:15.630",
"Id": "211439",
"ParentId": "211436",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211439",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T21:03:56.673",
"Id": "211436",
"Score": "1",
"Tags": [
"java",
"number-systems"
],
"Title": "Simple Binary to Decimal Converter"
} | 211436 |
<p>This is an implementation of the Sieve of Eratosthenes :</p>
<ul>
<li><p>It takes advantages of the fact that all primes from 5 and above can be written as <a href="https://primes.utm.edu/notes/faq/six.html" rel="nofollow noreferrer"><code>6X-1</code> or <code>6X+1</code></a>,</p></li>
<li><p>For better space complexity, it uses a pretty accurate <code>upperbound</code>. Better estimations of the upper bound can be found <a href="https://arxiv.org/pdf/1002.0442.pdf" rel="nofollow noreferrer">here</a>. I've observed a very slight increase in performance with this.</p></li>
</ul>
<hr>
<pre><code>func eratosthenesSieve(to n: Int) -> [Int] {
guard 2 <= n else { return [] }
var composites = Array(repeating: false, count: n + 1)
var primes: [Int] = []
let d = Double(n)
let upperBound = Int((d / log(d)) * (1.0 + 1.2762/log(d)))
primes.reserveCapacity(upperBound)
let squareRootN = Int(d.squareRoot())
//2 and 3
var p = 2
let twoOrThree = min(n, 3)
while p <= twoOrThree {
primes.append(p)
var q = p * p
let step = p * (p - 1)
while q <= n {
composites[q] = true
q += step
}
p += 1
}
//5 and above
p += 1
while p <= squareRootN {
for i in 0..<2 {
let nbr = p + 2 * i
if !composites[nbr] {
primes.append(nbr)
var q = nbr * nbr
var coef = 2 * (i + 1)
while q <= n {
composites[q] = true
q += coef * nbr
coef = 6 - coef
}
}
}
p += 6
}
while p <= n {
for i in 0..<2 {
let nbr = p + 2 * i
if nbr <= n && !composites[nbr] {
primes.append(nbr)
}
}
p += 6
}
return primes
}
</code></pre>
<hr>
<p>It was inspired by <a href="https://codereview.stackexchange.com/a/192042/49921">this</a> code by <a href="https://codereview.stackexchange.com/users/35991/martin-r">Mr Martin</a>.</p>
<p>Using the same benchmarking code in that answer, adding a fourth fractional digit in the timing results, plus some formatting, here are the results :</p>
<pre><code> ---------------------------------------------------------------
| | Nbr | Time (sec) |
| Up to | of |------------------------------|
| | Primes | Martin's | This |
|----------------|-------------|------------------------------|
| 100_000 | 9592 | 0.0008 | 0.0004 |
|----------------|-------------|--------------|---------------|
| 1_000_000 | 78_498 | 0.0056 | 0.0026 |
|----------------|-------------|--------------|---------------|
| 10_000_000 | 664_579 | 0.1233 | 0.0426 |
|----------------|-------------|--------------|---------------|
| 100_000_000 | 5_761_455 | 1.0976 | 0.5089 |
|----------------|-------------|--------------|---------------|
| 1_000_000_000 | 50_847_534 | 12.1328 | 5.9759 |
|----------------|-------------|--------------|---------------|
| 10_000_000_000 | 455_052_511 | 165.5658 | 84.5477 |
|----------------|-------------|--------------|---------------|
</code></pre>
<p>Using <a href="https://github.com/attaswift/Attabench" rel="nofollow noreferrer">Attabench</a>, here is a visual representation of the performance of both codes while <code>n</code> is less than <code>2^16</code>:</p>
<p><a href="https://i.stack.imgur.com/loDUM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/loDUM.png" alt="Attabench results"></a></p>
<hr>
<p>One thing I observe is some elements in the <code>composites</code> array are marked with <code>true</code> multiple times. This is expected (but unwanted) behavior since <code>6X-1</code> or <code>6X+1</code> aren't all primes. </p>
<p>What I'm looking for is making <strong>this</strong> Sieve of Eratosthenes quicker. I'm well aware of faster methods of finding primes. </p>
<p>Naming, code clarity, conciseness, consistency, etc, are welcome but are <strong>not</strong> the main point here.</p>
| [] | [
{
"body": "<blockquote>\n <p>It takes advantages of the fact that all primes from 5 and above can be written as 6X-1 or 6X+1,</p>\n</blockquote>\n\n<p>I don't think it does, really. It structures the code around that fact, but to take advantage of it, <em>at a minimum</em> you should replace</p>\n\n<blockquote>\n<pre><code> while p <= twoOrThree {\n primes.append(p)\n var q = p * p\n let step = p * (p - 1)\n while q <= n {\n composites[q] = true\n q += step\n }\n p += 1\n }\n</code></pre>\n</blockquote>\n\n<p>with</p>\n\n<pre><code> while p <= twoOrThree {\n primes.append(p)\n p += 1\n }\n</code></pre>\n\n<p>which in my testing gives a significant speedup.</p>\n\n<hr>\n\n<p>To maximise the advantage, you could reduce <code>composites</code> to only store flags for <span class=\"math-container\">\\$6X \\pm 1\\$</span>. Proof of concept code (could be tidier):</p>\n\n<pre><code> var pidx = 1\n p = 5\n while p <= squareRootN {\n if !composites[pidx] {\n primes.append(p)\n\n var qidx = 3 * pidx * (pidx + 2) + 1 + (pidx & 1)\n let delta = p << 1\n let off = (4 - 2 * (pidx & 1)) * pidx + 1\n while qidx < composites.count {\n composites[qidx - off] = true\n composites[qidx] = true\n qidx += delta\n }\n if qidx - off < composites.count {\n composites[qidx - off] = true\n }\n }\n\n pidx += 1\n p += 2 + 2 * (pidx & 1)\n }\n\n while p <= n {\n if !composites[pidx] { primes.append(p) }\n pidx += 1\n p += 2 + 2 * (pidx & 1)\n }\n</code></pre>\n\n<p>This gives a moderate speedup in my testing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T13:06:50.623",
"Id": "408900",
"Score": "0",
"body": "Thank you for the answer. [Here](https://imgur.com/a/ExAniDF) are the benchmarks, and they favor the code in the question (`original` being Martin's, and `eratosthenes2` is the code in your answer). Attabench confirms the benchmarks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T14:02:23.980",
"Id": "408904",
"Score": "0",
"body": "@Carpsen90, I don't know Swift and there seem to be some subtleties around imports which both this question and the answer you reference brush under the table, but I compared a tweaked version of your code with my code on https://tio.run/ . [Full tested code](https://gist.github.com/pjt33/73e47998812e65b1e1a21df3ec70c07f). I see user time: 12.470 s for your code and 7.002 s for mine. tio.run isn't ideal for benchmarking, but that's a significant improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T14:04:23.817",
"Id": "408905",
"Score": "0",
"body": "(I suspect the problem is that you've benchmarked my code sieving three times as far as your code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T15:03:24.393",
"Id": "408920",
"Score": "0",
"body": "The benchmarks were correct and can still be reproduced. You didn't mention in your answer this line `var composites = Array(repeating: false, count: n / 3 + 1)`, which makes all the difference. [Here](https://imgur.com/a/qLi7p8M) are the new benchmarks which favor your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T15:27:07.167",
"Id": "408921",
"Score": "0",
"body": "The answer is intended to be a code review, not a patch."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T11:23:15.027",
"Id": "211468",
"ParentId": "211437",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T21:33:48.730",
"Id": "211437",
"Score": "2",
"Tags": [
"performance",
"primes",
"swift",
"sieve-of-eratosthenes"
],
"Title": "Faster Sieve of Eratosthenes"
} | 211437 |
<p>I wrote code which calculates:</p>
<ol>
<li>Decile threshold for every decile group</li>
<li>Total income in the decile group</li>
<li>Number of persons</li>
<li>Share of decile in total income (%)</li>
<li>Tax</li>
<li>Share of tax (%)</li>
</ol>
<p>But unfortunately I didn't wrote with function like e.g apply, lapply, aggregate or similar function, so my code had around 150 lines. Can anybody help me to make this code simpler with some function like apply or something similar?</p>
<p>Output of my code you can see in this picture:</p>
<p><a href="https://i.stack.imgur.com/qQWiA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qQWiA.jpg" alt="enter image description here"></a></p>
<pre><code> [![`
library(dplyr)
set.seed(1444)
data1<-data.frame(sample(1000))
data2<-mutate(data1,TAX=sample.1000.*0.15)
colnames(data2)<-c("NET_INCOME","TAX")
# CALCULATION....
decili_total_income_neto<-data.frame(quantile(data2$NET_INCOME, c(.10, .20, .30, .40, .50, .60, .70, .80, .90, 1)))
ZBIR_TOTAL_NET_INCOME<-sum(data2$NET_INCOME)
ZBIR_TOTAL_TAX<-sum(data2$TAX)
#DECILE 1
t_prag_top_total_income_10<-decili_total_income_neto\[1,1\]
t_prag_top_total_income_filter_10<-filter(data2, NET_INCOME>= 0, NET_INCOME<= t_prag_top_total_income_10)
t_prag_top_total_income_filter_10_tax<-sum(t_prag_top_total_income_filter_10$TAX)
t_tax_share_10<-((t_prag_top_total_income_filter_10_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_10<-sum(t_prag_top_total_income_filter_10$NET_INCOME)
t_prag_top_total_income_filter_10a<-nrow(filter(data2, NET_INCOME>= 0, NET_INCOME<= t_prag_top_total_income_10))
t_prag_top_total_income_10b<-((t_prag_top_total_income_filter_10)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_DECILE_TABLE<-data.frame(cbind(t_prag_top_total_income_10,t_prag_top_total_income_filter_10,t_prag_top_total_income_filter_10a,t_prag_top_total_income_10b,t_prag_top_total_income_filter_10_tax , t_tax_share_10))
colnames(FINAL_DECILE_TABLE)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
#DECILE 2
t_prag_top_total_income_20<-decili_total_income_neto\[2,1\]
t_prag_top_total_income_filter_20<-filter(data2, NET_INCOME> t_prag_top_total_income_10, NET_INCOME<=t_prag_top_total_income_20)
t_prag_top_total_income_filter_20_tax<-sum(t_prag_top_total_income_filter_20$TAX)
t_tax_share_20<-((t_prag_top_total_income_filter_20_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_20<-sum(t_prag_top_total_income_filter_20$NET_INCOME)
t_prag_top_total_income_filter_20a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_10, NET_INCOME<=t_prag_top_total_income_20))
t_prag_top_total_income_20b<-((t_prag_top_total_income_filter_20)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE20<-data.frame(cbind(t_prag_top_total_income_20,t_prag_top_total_income_filter_20,t_prag_top_total_income_filter_20a,t_prag_top_total_income_20b,t_prag_top_total_income_filter_20_tax , t_tax_share_20))
colnames(FINAL_CENTILE_TABLE20)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE20)
#DECILE 3
t_prag_top_total_income_30<-decili_total_income_neto\[3,1\]
t_prag_top_total_income_filter_30<-filter(data2, NET_INCOME> t_prag_top_total_income_20, NET_INCOME<=t_prag_top_total_income_30)
t_prag_top_total_income_filter_30_tax<-sum(t_prag_top_total_income_filter_30$TAX)
t_tax_share_30<-((t_prag_top_total_income_filter_30_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_30<-sum(t_prag_top_total_income_filter_30$NET_INCOME)
t_prag_top_total_income_filter_30a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_20, NET_INCOME<=t_prag_top_total_income_30))
t_prag_top_total_income_30b<-((t_prag_top_total_income_filter_30)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE30<-data.frame(cbind(t_prag_top_total_income_30,t_prag_top_total_income_filter_30,t_prag_top_total_income_filter_30a,t_prag_top_total_income_30b,t_prag_top_total_income_filter_30_tax , t_tax_share_30))
colnames(FINAL_CENTILE_TABLE30)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE30)
#DECILE 4
t_prag_top_total_income_40<-decili_total_income_neto\[4,1\]
t_prag_top_total_income_filter_40<-filter(data2, NET_INCOME> t_prag_top_total_income_30, NET_INCOME<=t_prag_top_total_income_40)
t_prag_top_total_income_filter_40_tax<-sum(t_prag_top_total_income_filter_40$TAX)
t_tax_share_40<-((t_prag_top_total_income_filter_40_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_40<-sum(t_prag_top_total_income_filter_40$NET_INCOME)
t_prag_top_total_income_filter_40a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_30, NET_INCOME<=t_prag_top_total_income_40))
t_prag_top_total_income_40b<-((t_prag_top_total_income_filter_40)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE40<-data.frame(cbind(t_prag_top_total_income_40,t_prag_top_total_income_filter_40,t_prag_top_total_income_filter_40a,t_prag_top_total_income_40b,t_prag_top_total_income_filter_40_tax , t_tax_share_40))
colnames(FINAL_CENTILE_TABLE40)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE40)
#DECILE 5
t_prag_top_total_income_50<-decili_total_income_neto\[5,1\]
t_prag_top_total_income_filter_50<-filter(data2, NET_INCOME> t_prag_top_total_income_40, NET_INCOME<=t_prag_top_total_income_50)
t_prag_top_total_income_filter_50_tax<-sum(t_prag_top_total_income_filter_50$TAX)
t_tax_share_50<-((t_prag_top_total_income_filter_50_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_50<-sum(t_prag_top_total_income_filter_50$NET_INCOME)
t_prag_top_total_income_filter_50a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_40, NET_INCOME<=t_prag_top_total_income_50))
t_prag_top_total_income_50b<-((t_prag_top_total_income_filter_50)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE50<-data.frame(cbind(t_prag_top_total_income_50,t_prag_top_total_income_filter_50,t_prag_top_total_income_filter_50a,t_prag_top_total_income_50b,t_prag_top_total_income_filter_50_tax , t_tax_share_50))
colnames(FINAL_CENTILE_TABLE50)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE50)
#DECILE 6
t_prag_top_total_income_60<-decili_total_income_neto\[6,1\]
t_prag_top_total_income_filter_60<-filter(data2, NET_INCOME> t_prag_top_total_income_50, NET_INCOME<=t_prag_top_total_income_60)
t_prag_top_total_income_filter_60_tax<-sum(t_prag_top_total_income_filter_60$TAX)
t_tax_share_60<-((t_prag_top_total_income_filter_60_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_60<-sum(t_prag_top_total_income_filter_60$NET_INCOME)
t_prag_top_total_income_filter_60a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_50, NET_INCOME<=t_prag_top_total_income_60))
t_prag_top_total_income_60b<-((t_prag_top_total_income_filter_60)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE60<-data.frame(cbind(t_prag_top_total_income_60,t_prag_top_total_income_filter_60,t_prag_top_total_income_filter_60a,t_prag_top_total_income_60b,t_prag_top_total_income_filter_60_tax , t_tax_share_60))
colnames(FINAL_CENTILE_TABLE60)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE60)
#DECILE 7
t_prag_top_total_income_70<-decili_total_income_neto\[7,1\]
t_prag_top_total_income_filter_70<-filter(data2, NET_INCOME> t_prag_top_total_income_60, NET_INCOME<=t_prag_top_total_income_70)
t_prag_top_total_income_filter_70_tax<-sum(t_prag_top_total_income_filter_70$TAX)
t_tax_share_70<-((t_prag_top_total_income_filter_70_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_70<-sum(t_prag_top_total_income_filter_70$NET_INCOME)
t_prag_top_total_income_filter_70a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_60, NET_INCOME<=t_prag_top_total_income_70))
t_prag_top_total_income_70b<-((t_prag_top_total_income_filter_70)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE70<-data.frame(cbind(t_prag_top_total_income_70,t_prag_top_total_income_filter_70,t_prag_top_total_income_filter_70a,t_prag_top_total_income_70b,t_prag_top_total_income_filter_70_tax , t_tax_share_70))
colnames(FINAL_CENTILE_TABLE70)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE70)
#DECILE 8
t_prag_top_total_income_80<-decili_total_income_neto\[8,1\]
t_prag_top_total_income_filter_80<-filter(data2, NET_INCOME> t_prag_top_total_income_70, NET_INCOME<=t_prag_top_total_income_80)
t_prag_top_total_income_filter_80_tax<-sum(t_prag_top_total_income_filter_80$TAX)
t_tax_share_80<-((t_prag_top_total_income_filter_80_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_80<-sum(t_prag_top_total_income_filter_80$NET_INCOME)
t_prag_top_total_income_filter_80a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_70, NET_INCOME<=t_prag_top_total_income_80))
t_prag_top_total_income_80b<-((t_prag_top_total_income_filter_80)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE80<-data.frame(cbind(t_prag_top_total_income_80,t_prag_top_total_income_filter_80,t_prag_top_total_income_filter_80a,t_prag_top_total_income_80b,t_prag_top_total_income_filter_80_tax , t_tax_share_80))
colnames(FINAL_CENTILE_TABLE80)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE80)
#DECILE 9
t_prag_top_total_income_90<-decili_total_income_neto\[9,1\]
t_prag_top_total_income_filter_90<-filter(data2, NET_INCOME> t_prag_top_total_income_80, NET_INCOME<=t_prag_top_total_income_90)
t_prag_top_total_income_filter_90_tax<-sum(t_prag_top_total_income_filter_90$TAX)
t_tax_share_90<-((t_prag_top_total_income_filter_90_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_90<-sum(t_prag_top_total_income_filter_90$NET_INCOME)
t_prag_top_total_income_filter_90a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_80, NET_INCOME<=t_prag_top_total_income_90))
t_prag_top_total_income_90b<-((t_prag_top_total_income_filter_90)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE90<-data.frame(cbind(t_prag_top_total_income_90,t_prag_top_total_income_filter_90,t_prag_top_total_income_filter_90a,t_prag_top_total_income_90b,t_prag_top_total_income_filter_90_tax , t_tax_share_90))
colnames(FINAL_CENTILE_TABLE90)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE90)
#DECILE 10
t_prag_top_total_income_100<-decili_total_income_neto\[10,1\]
t_prag_top_total_income_filter_100<-filter(data2, NET_INCOME> t_prag_top_total_income_90, NET_INCOME<=t_prag_top_total_income_100)
t_prag_top_total_income_filter_100_tax<-sum(t_prag_top_total_income_filter_100$TAX)
t_tax_share_100<-((t_prag_top_total_income_filter_100_tax)/ZBIR_TOTAL_TAX)*100
t_prag_top_total_income_filter_100<-sum(t_prag_top_total_income_filter_100$NET_INCOME)
t_prag_top_total_income_filter_100a<-nrow(filter(data2, NET_INCOME> t_prag_top_total_income_90, NET_INCOME<=t_prag_top_total_income_100))
t_prag_top_total_income_100b<-((t_prag_top_total_income_filter_100)/ZBIR_TOTAL_NET_INCOME)*100
FINAL_CENTILE_TABLE100<-data.frame(cbind(t_prag_top_total_income_100,t_prag_top_total_income_filter_100,t_prag_top_total_income_filter_100a,t_prag_top_total_income_100b,t_prag_top_total_income_filter_100_tax,t_tax_share_100))
colnames(FINAL_CENTILE_TABLE100)<-c("Decile threshold","Total income in the decile","Number of persons in the centile","Share of the decile in total income (%)","Tax","Share tax(%)")
FINAL_DECILE_TABLE <- rbind(FINAL_DECILE_TABLE, FINAL_CENTILE_TABLE100)
View(FINAL_DECILE_TABLE)][1]][1]
</code></pre>
| [] | [
{
"body": "<p>The <code>dplyr</code> package you are using here is perfect for this kind of aggregation work. Of particular interest here will be the functions</p>\n\n<ol>\n<li><code>ntile()</code> for creating a DECILE (1 through 10) vector added to your data via <code>mutate()</code></li>\n<li><code>group_by()</code> for doing aggregation work per the newly created DECILE column</li>\n<li><code>summarize</code> for aggregating data within each group</li>\n</ol>\n\n<p>In action, it gives:</p>\n\n<pre><code>data <- data.frame(NET_INCOME = sample(1000)) %>%\n mutate(TAX = 0.15 * NET_INCOME)\n\nreport <- data %>%\n mutate(DECILE = ntile(NET_INCOME, 10)) %>%\n group_by(DECILE) %>%\n summarize(\n MAX_INCOME = max(NET_INCOME),\n NET_INCOME = sum(NET_INCOME),\n TAX = sum(TAX),\n COUNT = n(),\n ) %>%\n mutate(\n PCT_INCOME = 100 * NET_INCOME / sum(NET_INCOME),\n PCT_TAX = 100 * TAX / sum(TAX)\n ) %>% print\n\n# DECILE MAX_INCOME NET_INCOME TAX COUNT PCT_INCOME PCT_TAX\n# <int> <dbl> <int> <dbl> <int> <dbl> <dbl>\n# 1 1 100 5050 757.5 100 1.008991 1.008991\n# 2 2 200 15050 2257.5 100 3.006993 3.006993\n# 3 3 300 25050 3757.5 100 5.004995 5.004995\n# 4 4 400 35050 5257.5 100 7.002997 7.002997\n# 5 5 500 45050 6757.5 100 9.000999 9.000999\n# 6 6 600 55050 8257.5 100 10.999001 10.999001\n# 7 7 700 65050 9757.5 100 12.997003 12.997003\n# 8 8 800 75050 11257.5 100 14.995005 14.995005\n# 9 9 900 85050 12757.5 100 16.993007 16.993007\n# 10 10 1000 95050 14257.5 100 18.991009 18.991009\n</code></pre>\n\n<hr>\n\n<p>For comparison, this is how we could do with basic R functions. Using</p>\n\n<ol>\n<li><code>quantile</code> and <code>findInterval</code> (an alternative is <code>cut</code>) for building a vector of deciles (1 through 10)</li>\n<li><code>aggregate</code> to compute the sums per decile</li>\n</ol>\n\n<p>See for yourself:</p>\n\n<pre><code>set.seed(1444)\nnet_income <- sample(1000)\ndeciles <- quantile(net_income, seq(1, 10) / 10)\n\ndata <- data.frame(\n NET_INCOME = net_income,\n TAX = 0.15 * net_income,\n DECILE = findInterval(net_income, c(-Inf, deciles), rightmost.closed = TRUE),\n COUNT = 1 \n)\n\nper_decile <- aggregate(. ~ DECILE, data, FUN = sum)\nper_total <- aggregate(. ~ 1, data, FUN = sum)\n\ndata.frame(\n INCOME_THRESHOLD = deciles,\n DECILE = per_decile$DECILE,\n NET_INCOME = per_decile$NET_INCOME,\n COUNT = per_decile$COUNT,\n PCT_INCOME = 100 * per_decile$NET_INCOME / per_total$NET_INCOME,\n TAX = per_decile$TAX,\n PCT_TAX = 100 * per_decile$TAX / per_total$TAX\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T23:20:25.430",
"Id": "211443",
"ParentId": "211438",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211443",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T21:40:46.393",
"Id": "211438",
"Score": "0",
"Tags": [
"r"
],
"Title": "Calculate decile table with some loop in R"
} | 211438 |
<p>Code review/feedback is requested and appreciated for the following open-source <a href="https://en.wikipedia.org/wiki/Automatic_differentiation" rel="nofollow noreferrer">automatic differentiation</a> C++ header-only library released under the Boost License. I am the author.</p>
<p><a href="https://github.com/pulver/autodiff" rel="nofollow noreferrer">https://github.com/pulver/autodiff</a></p>
<p>This library facilitates the calculation of nth-order single and multi-variable derivatives of functions using forward-mode automatic differentiation.</p>
<pre><code>#ifndef BOOST_MATH_AUTODIFF_HPP
#define BOOST_MATH_AUTODIFF_HPP
#include <boost/config.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/factorials.hpp>
#include <boost/math/tools/promotion.hpp>
#include <algorithm>
#include <array>
#include <cmath>
#include <functional>
#include <initializer_list>
#include <limits>
#include <numeric>
#include <ostream>
#include <type_traits>
// Automatic Differentiation v1
namespace boost { namespace math { namespace differentiation { namespace autodiff { inline namespace v1 {
// Use variable<> instead of dimension<> or nested_dimensions<>.
template<typename RealType,size_t Order>
class dimension;
template<typename RealType,size_t Order,size_t... Orders> // specialized for dimension<> below.
struct nested_dimensions { using type = dimension<typename nested_dimensions<RealType,Orders...>::type,Order>; };
// The variable<> alias is the primary template for instantiating autodiff variables.
// This nests one or more dimension<> classes together into a multi-dimensional type.
template<typename RealType,size_t Order,size_t... Orders>
using variable = typename nested_dimensions<RealType,Order,Orders...>::type;
////////////////////////////////////////////////////////////////////////////////
template<typename RealType0,typename RealType1,typename... RealTypes>
struct promote_args_n { using type = typename boost::math::tools::promote_args_2<RealType0,
typename promote_args_n<RealType1,RealTypes...>::type>::type; };
template<typename RealType0,typename RealType1,typename... RealTypes>
using promote = typename promote_args_n<RealType0,RealType1,RealTypes...>::type;
// Get non-dimension<> root type T of variable<T,O0,O1,O2,...>.
template<typename RealType>
struct root_type_finder { using type = RealType; }; // specialized for dimension<> below.
template<typename RealType,size_t Depth>
struct type_at { using type = RealType; }; // specialized for dimension<> below.
// Satisfies Boost's Conceptual Requirements for Real Number Types.
template<typename RealType,size_t Order>
class dimension
{
std::array<RealType,Order+1> v;
public:
using root_type = typename root_type_finder<RealType>::type; // RealType in the root dimension<RealType,Order>.
dimension() = default;
// RealType(cr) | RealType | RealType is copy constructible.
dimension(const dimension<RealType,Order>&) = default;
// Be aware of implicit casting from one dimension<> type to another by this copy constructor.
template<typename RealType2,size_t Order2>
dimension<RealType,Order>(const dimension<RealType2,Order2>&);
// RealType(ca) | RealType | RealType is copy constructible from the arithmetic types.
explicit dimension(const root_type&); // Initialize a variable of differentiation.
explicit dimension(const std::initializer_list<root_type>&); // Initialize a constant.
// r = cr | RealType& | Assignment operator.
dimension<RealType,Order>& operator=(const dimension<RealType,Order>&) = default;
// r = ca | RealType& | Assignment operator from the arithmetic types.
dimension<RealType,Order>& operator=(const root_type&); // Set a constant.
// r += cr | RealType& | Adds cr to r.
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& operator+=(const dimension<RealType2,Order2>&);
// r += ca | RealType& | Adds ar to r.
dimension<RealType,Order>& operator+=(const root_type&);
// r -= cr | RealType& | Subtracts cr from r.
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& operator-=(const dimension<RealType2,Order2>&);
// r -= ca | RealType& | Subtracts ca from r.
dimension<RealType,Order>& operator-=(const root_type&);
// r *= cr | RealType& | Multiplies r by cr.
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& operator*=(const dimension<RealType2,Order2>&);
// r *= ca | RealType& | Multiplies r by ca.
dimension<RealType,Order>& operator*=(const root_type&);
// r /= cr | RealType& | Divides r by cr.
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& operator/=(const dimension<RealType2,Order2>&);
// r /= ca | RealType& | Divides r by ca.
dimension<RealType,Order>& operator/=(const root_type&);
// -r | RealType | Unary Negation.
dimension<RealType,Order> operator-() const;
// +r | RealType& | Identity Operation.
const dimension<RealType,Order>& operator+() const;
// cr + cr2 | RealType | Binary Addition
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> operator+(const dimension<RealType2,Order2>&) const;
// cr + ca | RealType | Binary Addition
dimension<RealType,Order> operator+(const root_type&) const;
// ca + cr | RealType | Binary Addition
template<typename RealType2,size_t Order2>
friend dimension<RealType2,Order2>
operator+(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr - cr2 | RealType | Binary Subtraction
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> operator-(const dimension<RealType2,Order2>&) const;
// cr - ca | RealType | Binary Subtraction
dimension<RealType,Order> operator-(const root_type&) const;
// ca - cr | RealType | Binary Subtraction
template<typename RealType2,size_t Order2>
friend dimension<RealType2,Order2>
operator-(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr * cr2 | RealType | Binary Multiplication
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> operator*(const dimension<RealType2,Order2>&) const;
// cr * ca | RealType | Binary Multiplication
dimension<RealType,Order> operator*(const root_type&) const;
// ca * cr | RealType | Binary Multiplication
template<typename RealType2,size_t Order2>
friend dimension<RealType2,Order2>
operator*(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr / cr2 | RealType | Binary Subtraction
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> operator/(const dimension<RealType2,Order2>&) const;
// cr / ca | RealType | Binary Subtraction
dimension<RealType,Order> operator/(const root_type&) const;
// ca / cr | RealType | Binary Subtraction
template<typename RealType2,size_t Order2>
friend dimension<RealType2,Order2>
operator/(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr == cr2 | bool | Equality Comparison
template<typename RealType2,size_t Order2> // This only compares the root term. All other terms are ignored.
bool operator==(const dimension<RealType2,Order2>&) const;
// cr == ca | bool | Equality Comparison
bool operator==(const root_type&) const;
// ca == cr | bool | Equality Comparison
template<typename RealType2,size_t Order2> // This only compares the root term. All other terms are ignored.
friend bool operator==(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr != cr2 | bool | Inequality Comparison
template<typename RealType2,size_t Order2>
bool operator!=(const dimension<RealType2,Order2>&) const;
// cr != ca | bool | Inequality Comparison
bool operator!=(const root_type&) const;
// ca != cr | bool | Inequality Comparison
template<typename RealType2,size_t Order2>
friend bool operator!=(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr <= cr2 | bool | Less than equal to.
template<typename RealType2,size_t Order2>
bool operator<=(const dimension<RealType2,Order2>&) const;
// cr <= ca | bool | Less than equal to.
bool operator<=(const root_type&) const;
// ca <= cr | bool | Less than equal to.
template<typename RealType2,size_t Order2>
friend bool operator<=(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr >= cr2 | bool | Greater than equal to.
template<typename RealType2,size_t Order2>
bool operator>=(const dimension<RealType2,Order2>&) const;
// cr >= ca | bool | Greater than equal to.
bool operator>=(const root_type&) const;
// ca >= cr | bool | Greater than equal to.
template<typename RealType2,size_t Order2>
friend bool operator>=(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr < cr2 | bool | Less than comparison.
template<typename RealType2,size_t Order2>
bool operator<(const dimension<RealType2,Order2>&) const;
// cr < ca | bool | Less than comparison.
bool operator<(const root_type&) const;
// ca < cr | bool | Less than comparison.
template<typename RealType2,size_t Order2>
friend bool operator<(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// cr > cr2 | bool | Greater than comparison.
template<typename RealType2,size_t Order2>
bool operator>(const dimension<RealType2,Order2>&) const;
// cr > ca | bool | Greater than comparison.
bool operator>(const root_type&) const;
// ca > cr | bool | Greater than comparison.
template<typename RealType2,size_t Order2>
friend bool operator>(const typename dimension<RealType2,Order2>::root_type&, const dimension<RealType2,Order2>&);
// Will throw std::out_of_range if Order < order.
template<typename... Orders>
typename type_at<RealType,sizeof...(Orders)>::type at(size_t order, Orders... orders) const;
template<typename... Orders>
typename type_at<RealType,sizeof...(Orders)-1>::type derivative(Orders... orders) const;
dimension<RealType,Order> inverse() const; // Multiplicative inverse.
static constexpr size_t depth(); // Number of nested std::array<RealType,Order>.
static constexpr size_t order_sum();
explicit operator root_type() const; // Must be explicit, otherwise overloaded operators are ambiguous.
dimension<RealType,Order>& set_root(const root_type&);
// Use when function returns derivatives.
dimension<RealType,Order> apply(const std::function<root_type(size_t)>&) const;
// Use when function returns derivative(i)/factorial(i) (slightly more efficient than apply().)
dimension<RealType,Order> apply_with_factorials(const std::function<root_type(size_t)>&) const;
// Same as apply() but uses horner method. May be more accurate in some cases but not as good with inf derivatives.
dimension<RealType,Order> apply_with_horner(const std::function<root_type(size_t)>&) const;
// Same as apply_with_factorials() but uses horner method.
dimension<RealType,Order> apply_with_horner_factorials(const std::function<root_type(size_t)>&) const;
private:
RealType epsilon_inner_product(size_t z0, size_t isum0, size_t m0,
const dimension<RealType,Order>& cr, size_t z1, size_t isum1, size_t m1, size_t j) const;
dimension<RealType,Order> epsilon_multiply(size_t z0, size_t isum0,
const dimension<RealType,Order>& cr, size_t z1, size_t isum1) const;
dimension<RealType,Order> epsilon_multiply(size_t z0, size_t isum0, const root_type& ca) const;
dimension<RealType,Order> inverse_apply() const;
dimension<RealType,Order>& multiply_assign_by_root_type(bool is_root, const root_type&);
template<typename RealType2,size_t Orders2>
friend class dimension;
template<typename RealType2,size_t Order2>
friend std::ostream& operator<<(std::ostream&, const dimension<RealType2,Order2>&);
// C++11 Compatibility
#ifdef BOOST_NO_CXX17_IF_CONSTEXPR
template<typename... Orders>
typename type_at<RealType, sizeof...(Orders)>::type at_cpp11(std::true_type, size_t order, Orders... orders) const;
template<typename... Orders>
typename type_at<RealType, sizeof...(Orders)>::type at_cpp11(std::false_type, size_t order, Orders... orders) const;
template<typename SizeType>
dimension<RealType,Order> epsilon_multiply_cpp11(std::true_type, SizeType z0, size_t isum0,
const dimension<RealType,Order>& cr, size_t z1, size_t isum1) const;
template<typename SizeType>
dimension<RealType,Order> epsilon_multiply_cpp11(std::false_type, SizeType z0, size_t isum0,
const dimension<RealType,Order>& cr, size_t z1, size_t isum1) const;
template<typename SizeType>
dimension<RealType,Order> epsilon_multiply_cpp11(std::true_type, SizeType z0, size_t isum0,
const root_type& ca) const;
template<typename SizeType>
dimension<RealType,Order> epsilon_multiply_cpp11(std::false_type, SizeType z0, size_t isum0,
const root_type& ca) const;
template<typename RootType>
dimension<RealType,Order>& multiply_assign_by_root_type_cpp11(std::true_type, bool is_root, const RootType& ca);
template<typename RootType>
dimension<RealType,Order>& multiply_assign_by_root_type_cpp11(std::false_type, bool is_root, const RootType& ca);
template<typename RootType>
dimension<RealType,Order>& set_root_cpp11(std::true_type, const RootType& root);
template<typename RootType>
dimension<RealType,Order>& set_root_cpp11(std::false_type, const RootType& root);
#endif
};
// Standard Library Support Requirements
// fabs(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> fabs(const dimension<RealType,Order>&);
// abs(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> abs(const dimension<RealType,Order>&);
// ceil(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> ceil(const dimension<RealType,Order>&);
// floor(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> floor(const dimension<RealType,Order>&);
// exp(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> exp(const dimension<RealType,Order>&);
// pow(cr, ca) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> pow(const dimension<RealType,Order>&,const typename dimension<RealType,Order>::root_type&);
// pow(ca, cr) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> pow(const typename dimension<RealType,Order>::root_type&,const dimension<RealType,Order>&);
// pow(cr1, cr2) | RealType
template<typename RealType1,size_t Order1,typename RealType2,size_t Order2>
promote<dimension<RealType1,Order1>,dimension<RealType2,Order2>>
pow(const dimension<RealType1,Order1>&, const dimension<RealType2,Order2>&);
// sqrt(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> sqrt(const dimension<RealType,Order>&);
// log(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> log(const dimension<RealType,Order>&);
// frexp(cr1, &i) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> frexp(const dimension<RealType,Order>&, int*);
// ldexp(cr1, i) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> ldexp(const dimension<RealType,Order>&, int);
// cos(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> cos(const dimension<RealType,Order>&);
// sin(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> sin(const dimension<RealType,Order>&);
// asin(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> asin(const dimension<RealType,Order>&);
// tan(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> tan(const dimension<RealType,Order>&);
// atan(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> atan(const dimension<RealType,Order>&);
// fmod(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> fmod(const dimension<RealType,Order>&, const typename dimension<RealType,Order>::root_type&);
// round(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> round(const dimension<RealType,Order>&);
// iround(cr1) | int
template<typename RealType,size_t Order>
int iround(const dimension<RealType,Order>&);
// trunc(cr1) | RealType
template<typename RealType,size_t Order>
dimension<RealType,Order> trunc(const dimension<RealType,Order>&);
// itrunc(cr1) | int
template<typename RealType,size_t Order>
int itrunc(const dimension<RealType,Order>&);
// Additional functions
template<typename RealType,size_t Order>
dimension<RealType,Order> acos(const dimension<RealType,Order>&);
template<typename RealType,size_t Order>
dimension<RealType,Order> erfc(const dimension<RealType,Order>&);
template<typename RealType,size_t Order>
long lround(const dimension<RealType,Order>&);
template<typename RealType,size_t Order>
long long llround(const dimension<RealType,Order>&);
template<typename RealType,size_t Order>
long double truncl(const dimension<RealType,Order>&);
template<typename RealType,size_t Order>
struct nested_dimensions<RealType,Order> { using type = dimension<RealType,Order>; };
template<typename RealType0,typename RealType1>
struct promote_args_n<RealType0,RealType1>
{
using type = typename boost::math::tools::promote_args_2<RealType0,RealType1>::type;
};
template<typename RealType,size_t Order>
struct root_type_finder<dimension<RealType,Order>> { using type = typename root_type_finder<RealType>::type; };
// Specialization of type_at<> for dimension<>. Examples:
// * type_at<T,0>::type is T.
// * type_at<dimension<T,O1>,1>::type is T.
// * type_at<dimension<dimension<T,O2>,O1>,2>::type is T.
// * type_at<dimension<dimension<dimension<T,O3>,O2>,O1>,3>::type is T.
template<typename RealType,size_t Order,size_t Depth>
struct type_at<dimension<RealType,Order>,Depth>
{
using type =
typename std::conditional<Depth==0,dimension<RealType,Order>,typename type_at<RealType,Depth-1>::type>::type;
};
// Compile-time test for dimension<> type.
template<typename>
struct is_dimension : std::false_type {};
template<typename RealType,size_t Order>
struct is_dimension<dimension<RealType,Order>> : std::true_type {};
// C++11 compatibility
#ifdef BOOST_NO_CXX17_IF_CONSTEXPR
# define BOOST_AUTODIFF_IF_CONSTEXPR
#else
# define BOOST_AUTODIFF_IF_CONSTEXPR constexpr
#endif
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
dimension<RealType,Order>::dimension(const dimension<RealType2,Order2>& cr)
{
if BOOST_AUTODIFF_IF_CONSTEXPR (is_dimension<RealType2>::value)
for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)
v[i] = RealType(cr.v[i]);
else
for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)
v[i] = cr.v[i];
if BOOST_AUTODIFF_IF_CONSTEXPR (Order2 < Order)
std::fill(v.begin()+(Order2+1), v.end(), RealType{0});
}
// Note difference between arithmetic constructors and arithmetic assignment:
// * non-initializer_list arithmetic constructor creates a variable dimension (epsilon coefficient = 1).
// * initializer_list arithmetic constructor creates a constant dimension (epsilon coefficient = 0).
// * arithmetic assignment creates a constant (epsilon coefficients = 0).
template<typename RealType,size_t Order>
dimension<RealType,Order>::dimension(const root_type& ca)
: v{{static_cast<RealType>(ca)}}
{
if BOOST_AUTODIFF_IF_CONSTEXPR (depth() == 1 && 0 < Order)
v[1] = static_cast<root_type>(1); // Set epsilon coefficient = 1.
}
template<typename RealType,size_t Order>
dimension<RealType,Order>::dimension(const std::initializer_list<root_type>& list)
: v{}
{
for (size_t i=0 ; i<std::min(Order+1,list.size()) ; ++i)
v[i] = *(list.begin()+i);
}
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::operator=(const root_type& ca)
{
v.front() = RealType{ca};
if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order)
std::fill(v.begin()+1, v.end(), RealType{0});
return *this;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& dimension<RealType,Order>::operator+=(const dimension<RealType2,Order2>& cr)
{
for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)
v[i] += cr.v[i];
return *this;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::operator+=(const root_type& ca)
{
v.front() += ca;
return *this;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& dimension<RealType,Order>::operator-=(const dimension<RealType2,Order2>& cr)
{
for (size_t i=0 ; i<=Order ; ++i)
v[i] -= cr.v[i];
return *this;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::operator-=(const root_type& ca)
{
v.front() -= ca;
return *this;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& dimension<RealType,Order>::operator*=(const dimension<RealType2,Order2>& cr)
{
const promote<RealType,RealType2> zero{0};
if BOOST_AUTODIFF_IF_CONSTEXPR (Order <= Order2)
for (size_t i=0, j=Order ; i<=Order ; ++i, --j)
v[j] = std::inner_product(v.cbegin(), v.cend()-i, cr.v.crbegin()+i, zero);
else
{
for (size_t i=0, j=Order ; i<=Order-Order2 ; ++i, --j)
v[j] = std::inner_product(cr.v.cbegin(), cr.v.cend(), v.crbegin()+i, zero);
for (size_t i=Order-Order2+1, j=Order2-1 ; i<=Order ; ++i, --j)
v[j] = std::inner_product(cr.v.cbegin(), cr.v.cbegin()+(j+1), v.crbegin()+i, zero);
}
return *this;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::operator*=(const root_type& ca)
{
return multiply_assign_by_root_type(true, ca);
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
dimension<RealType,Order>& dimension<RealType,Order>::operator/=(const dimension<RealType2,Order2>& cr)
{
const RealType zero{0};
v.front() /= cr.v.front();
if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)
for (size_t i=1, j=Order2-1, k=Order ; i<=Order ; ++i, --j, --k)
(v[i] -= std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, v.crbegin()+k, zero)) /= cr.v.front();
else if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order2)
for (size_t i=1, j=Order2-1, k=Order ; i<=Order ; ++i, j&&--j, --k)
(v[i] -= std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, v.crbegin()+k, zero)) /= cr.v.front();
else
for (size_t i=1 ; i<=Order ; ++i)
v[i] /= cr.v.front();
return *this;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::operator/=(const root_type& ca)
{
std::for_each(v.begin(), v.end(), [&ca](RealType& x) { x /= ca; });
return *this;
}
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::operator-() const
{
dimension<RealType,Order> retval;
for (size_t i=0 ; i<=Order ; ++i)
retval.v[i] = -v[i];
return retval;
}
template<typename RealType,size_t Order>
const dimension<RealType,Order>& dimension<RealType,Order>::operator+() const
{
return *this;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>>
dimension<RealType,Order>::operator+(const dimension<RealType2,Order2>& cr) const
{
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> retval;
for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)
retval.v[i] = v[i] + cr.v[i];
if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)
for (size_t i=Order+1 ; i<=Order2 ; ++i)
retval.v[i] = cr.v[i];
else if BOOST_AUTODIFF_IF_CONSTEXPR (Order2 < Order)
for (size_t i=Order2+1 ; i<=Order ; ++i)
retval.v[i] = v[i];
return retval;
}
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::operator+(const root_type& ca) const
{
dimension<RealType,Order> retval(*this);
retval.v.front() += ca;
return retval;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>
operator+(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return cr + ca;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>>
dimension<RealType,Order>::operator-(const dimension<RealType2,Order2>& cr) const
{
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> retval;
for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)
retval.v[i] = v[i] - cr.v[i];
if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)
for (size_t i=Order+1 ; i<=Order2 ; ++i)
retval.v[i] = -cr.v[i];
else if BOOST_AUTODIFF_IF_CONSTEXPR (Order2 < Order)
for (size_t i=Order2+1 ; i<=Order ; ++i)
retval.v[i] = v[i];
return retval;
}
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::operator-(const root_type& ca) const
{
dimension<RealType,Order> retval(*this);
retval.v.front() -= ca;
return retval;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>
operator-(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return -cr += ca;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>>
dimension<RealType,Order>::operator*(const dimension<RealType2,Order2>& cr) const
{
const promote<RealType,RealType2> zero{0};
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> retval;
if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)
for (size_t i=0, j=Order, k=Order2 ; i<=Order2 ; ++i, j&&--j, --k)
retval.v[i] = std::inner_product(v.cbegin(), v.cend()-j, cr.v.crbegin()+k, zero);
else
for (size_t i=0, j=Order2, k=Order ; i<=Order ; ++i, j&&--j, --k)
retval.v[i] = std::inner_product(cr.v.cbegin(), cr.v.cend()-j, v.crbegin()+k, zero);
return retval;
}
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::operator*(const root_type& ca) const
{
return dimension<RealType,Order>(*this) *= ca;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>
operator*(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return cr * ca;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
promote<dimension<RealType,Order>,dimension<RealType2,Order2>>
dimension<RealType,Order>::operator/(const dimension<RealType2,Order2>& cr) const
{
const promote<RealType,RealType2> zero{0};
promote<dimension<RealType,Order>,dimension<RealType2,Order2>> retval;
retval.v.front() = v.front() / cr.v.front();
if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)
{
for (size_t i=1, j=Order2-1 ; i<=Order ; ++i, --j)
retval.v[i] = (v[i] -
std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+(j+1), zero)) / cr.v.front();
for (size_t i=Order+1, j=Order2-Order-1 ; i<=Order2 ; ++i, --j)
retval.v[i] =
-std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+(j+1), zero) / cr.v.front();
}
else if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order2)
for (size_t i=1, j=Order2-1, k=Order ; i<=Order ; ++i, j&&--j, --k)
retval.v[i] =
(v[i] - std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+k, zero)) / cr.v.front();
else
for (size_t i=1 ; i<=Order ; ++i)
retval.v[i] = v[i] / cr.v.front();
return retval;
}
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::operator/(const root_type& ca) const
{
return dimension<RealType,Order>(*this) /= ca;
}
template<typename RealType,size_t Order>
dimension<RealType,Order>
operator/(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
dimension<RealType,Order> retval;
retval.v.front() = ca / cr.v.front();
if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order)
{
const RealType zero{0};
for (size_t i=1, j=Order-1 ; i<=Order ; ++i, --j)
retval.v[i] = -std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+(j+1), zero)
/ cr.v.front();
}
return retval;
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
bool dimension<RealType,Order>::operator==(const dimension<RealType2,Order2>& cr) const
{
return v.front() == cr.v.front();
}
template<typename RealType,size_t Order>
bool dimension<RealType,Order>::operator==(const root_type& ca) const
{
return v.front() == ca;
}
template<typename RealType,size_t Order>
bool operator==(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return ca == cr.v.front();
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
bool dimension<RealType,Order>::operator!=(const dimension<RealType2,Order2>& cr) const
{
return v.front() != cr.v.front();
}
template<typename RealType,size_t Order>
bool dimension<RealType,Order>::operator!=(const root_type& ca) const
{
return v.front() != ca;
}
template<typename RealType,size_t Order>
bool operator!=(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return ca != cr.v.front();
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
bool dimension<RealType,Order>::operator<=(const dimension<RealType2,Order2>& cr) const
{
return v.front() <= cr.v.front();
}
template<typename RealType,size_t Order>
bool dimension<RealType,Order>::operator<=(const root_type& ca) const
{
return v.front() <= ca;
}
template<typename RealType,size_t Order>
bool operator<=(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return ca <= cr.v.front();
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
bool dimension<RealType,Order>::operator>=(const dimension<RealType2,Order2>& cr) const
{
return v.front() >= cr.v.front();
}
template<typename RealType,size_t Order>
bool dimension<RealType,Order>::operator>=(const root_type& ca) const
{
return v.front() >= ca;
}
template<typename RealType,size_t Order>
bool operator>=(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return ca >= cr.v.front();
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
bool dimension<RealType,Order>::operator<(const dimension<RealType2,Order2>& cr) const
{
return v.front() < cr.v.front();
}
template<typename RealType,size_t Order>
bool dimension<RealType,Order>::operator<(const root_type& ca) const
{
return v.front() < ca;
}
template<typename RealType,size_t Order>
bool operator<(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return ca < cr.v.front();
}
template<typename RealType,size_t Order>
template<typename RealType2,size_t Order2>
bool dimension<RealType,Order>::operator>(const dimension<RealType2,Order2>& cr) const
{
return v.front() > cr.v.front();
}
template<typename RealType,size_t Order>
bool dimension<RealType,Order>::operator>(const root_type& ca) const
{
return v.front() > ca;
}
template<typename RealType,size_t Order>
bool operator>(const typename dimension<RealType,Order>::root_type& ca, const dimension<RealType,Order>& cr)
{
return ca > cr.v.front();
}
/*** Other methods and functions ***/
// f : order -> derivative(order)
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::apply(const std::function<root_type(size_t)>& f) const
{
const dimension<RealType,Order> epsilon = dimension<RealType,Order>(*this).set_root(0);
dimension<RealType,Order> epsilon_i = dimension<RealType,Order>{1}; // epsilon to the power of i
dimension<RealType,Order> accumulator = dimension<RealType,Order>{f(0)};
for (size_t i=1 ; i<=order_sum() ; ++i)
{ // accumulator += (epsilon_i *= epsilon) * (f(i) / boost::math::factorial<root_type>(i));
epsilon_i = epsilon_i.epsilon_multiply(i-1, 0, epsilon, 1, 0);
accumulator += epsilon_i.epsilon_multiply(i, 0, f(i) / boost::math::factorial<root_type>(i));
}
return accumulator;
}
// f : order -> derivative(order)/factorial(order)
// Use this when the computation of the derivatives already includes the factorial terms. E.g. See atan().
template<typename RealType,size_t Order>
dimension<RealType,Order>
dimension<RealType,Order>::apply_with_factorials(const std::function<root_type(size_t)>& f) const
{
const dimension<RealType,Order> epsilon = dimension<RealType,Order>(*this).set_root(0);
dimension<RealType,Order> epsilon_i = dimension<RealType,Order>{1}; // epsilon to the power of i
dimension<RealType,Order> accumulator = dimension<RealType,Order>{f(0)};
for (size_t i=1 ; i<=order_sum() ; ++i)
{ // accumulator += (epsilon_i *= epsilon) * f(i);
epsilon_i = epsilon_i.epsilon_multiply(i-1, 0, epsilon, 1, 0);
accumulator += epsilon_i.epsilon_multiply(i, 0, f(i));
}
return accumulator;
}
// f : order -> derivative(order)
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::apply_with_horner(const std::function<root_type(size_t)>& f) const
{
const dimension<RealType,Order> epsilon = dimension<RealType,Order>(*this).set_root(0);
auto accumulator = dimension<RealType,Order>{f(order_sum())/boost::math::factorial<root_type>(order_sum())};
for (size_t i=order_sum() ; i-- ;)
(accumulator *= epsilon) += f(i) / boost::math::factorial<root_type>(i);
return accumulator;
}
// f : order -> derivative(order)/factorial(order)
// Use this when the computation of the derivatives already includes the factorial terms. E.g. See atan().
template<typename RealType,size_t Order>
dimension<RealType,Order>
dimension<RealType,Order>::apply_with_horner_factorials(const std::function<root_type(size_t)>& f) const
{
const dimension<RealType,Order> epsilon = dimension<RealType,Order>(*this).set_root(0);
auto accumulator = dimension<RealType,Order>{f(order_sum())};
for (size_t i=order_sum() ; i-- ;)
(accumulator *= epsilon) += f(i);
return accumulator;
}
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
// Can throw "std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)"
template<typename RealType,size_t Order>
template<typename... Orders>
typename type_at<RealType,sizeof...(Orders)>::type dimension<RealType,Order>::at(size_t order, Orders... orders) const
{
if constexpr (0 < sizeof...(orders))
return v.at(order).at(orders...);
else
return v.at(order);
}
#endif
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
template<typename RealType,size_t Order>
constexpr size_t dimension<RealType,Order>::depth()
{
if constexpr (is_dimension<RealType>::value)
return 1 + RealType::depth();
else
return 1;
}
#endif
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
template<typename RealType,size_t Order>
constexpr size_t dimension<RealType,Order>::order_sum()
{
if constexpr (is_dimension<RealType>::value)
return Order + RealType::order_sum();
else
return Order;
}
#endif
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
// Can throw "std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)"
template<typename RealType,size_t Order>
template<typename... Orders>
typename type_at<RealType,sizeof...(Orders)-1>::type dimension<RealType,Order>::derivative(Orders... orders) const
{
static_assert(sizeof...(orders) <= depth(),
"Number of parameters to derivative(...) cannot exceed the number of dimensions in the dimension<...>.");
return at(orders...) * (... * boost::math::factorial<root_type>(orders));
}
#endif
template<typename RealType,size_t Order>
RealType dimension<RealType,Order>::epsilon_inner_product(size_t z0, size_t isum0, size_t m0,
const dimension<RealType,Order>& cr, size_t z1, size_t isum1, size_t m1, size_t j) const
{
static_assert(is_dimension<RealType>::value, "epsilon_inner_product() must have 1 < depth().");
RealType accumulator = RealType();
const size_t i0_max = m1 < j ? j-m1 : 0;
for (size_t i0=m0, i1=j-m0 ; i0<=i0_max ; ++i0, --i1)
accumulator += v.at(i0).epsilon_multiply(z0, isum0+i0, cr.v.at(i1), z1, isum1+i1);
return accumulator;
}
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::epsilon_multiply(size_t z0, size_t isum0,
const dimension<RealType,Order>& cr, size_t z1, size_t isum1) const
{
const RealType zero{0};
const size_t m0 = order_sum() + isum0 < Order + z0 ? Order + z0 - (order_sum() + isum0) : 0;
const size_t m1 = order_sum() + isum1 < Order + z1 ? Order + z1 - (order_sum() + isum1) : 0;
const size_t i_max = m0 + m1 < Order ? Order - (m0 + m1) : 0;
dimension<RealType,Order> retval = dimension<RealType,Order>();
if constexpr (is_dimension<RealType>::value)
for (size_t i=0, j=Order ; i<=i_max ; ++i, --j)
retval.v[j] = epsilon_inner_product(z0, isum0, m0, cr, z1, isum1, m1, j);
else
for (size_t i=0, j=Order ; i<=i_max ; ++i, --j)
retval.v[j] = std::inner_product(v.cbegin()+m0, v.cend()-(i+m1), cr.v.crbegin()+(i+m0), zero);
return retval;
}
#endif
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
// When called from outside this method, z0 should be non-zero. Otherwise if z0=0 then it will give an
// incorrect result of 0 when the root value is 0 and ca=inf, when instead the correct product is nan.
// If z0=0 then use the regular multiply operator*() instead.
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::epsilon_multiply(size_t z0, size_t isum0,
const root_type& ca) const
{
dimension<RealType,Order> retval(*this);
const size_t m0 = order_sum() + isum0 < Order + z0 ? Order + z0 - (order_sum() + isum0) : 0;
if constexpr (is_dimension<RealType>::value)
for (size_t i=m0 ; i<=Order ; ++i)
retval.v[i] = retval.v[i].epsilon_multiply(z0, isum0+i, ca);
else
for (size_t i=m0 ; i<=Order ; ++i)
if (retval.v[i] != static_cast<RealType>(0))
retval.v[i] *= ca;
return retval;
}
#endif
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::inverse() const
{
return operator root_type() == 0 ? inverse_apply() : 1 / *this;
}
// This gives autodiff::log(0.0) = depth(1)(-inf,inf,-inf,inf,-inf,inf)
// 1 / *this: autodiff::log(0.0) = depth(1)(-inf,inf,-inf,-nan,-nan,-nan)
template<typename RealType,size_t Order>
dimension<RealType,Order> dimension<RealType,Order>::inverse_apply() const
{
root_type derivatives[order_sum()+1]; // derivatives of 1/x
const root_type x0 = static_cast<root_type>(*this);
derivatives[0] = 1 / x0;
for (size_t i=1 ; i<=order_sum() ; ++i)
derivatives[i] = -derivatives[i-1] * i / x0;
return apply([&derivatives](size_t j) { return derivatives[j]; });
}
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::multiply_assign_by_root_type(bool is_root, const root_type& ca)
{
auto itr = v.begin();
if constexpr (is_dimension<RealType>::value)
{
itr->multiply_assign_by_root_type(is_root, ca);
for (++itr ; itr!=v.end() ; ++itr)
itr->multiply_assign_by_root_type(false, ca);
}
else
{
if (is_root || *itr != 0)
*itr *= ca; // Skip multiplication of 0 by ca=inf to avoid nan. Exception: root value is always multiplied.
for (++itr ; itr!=v.end() ; ++itr)
if (*itr != 0)
*itr *= ca;
}
return *this;
}
#endif
template<typename RealType,size_t Order>
dimension<RealType,Order>::operator root_type() const
{
return static_cast<root_type>(v.front());
}
#ifndef BOOST_NO_CXX17_IF_CONSTEXPR
template<typename RealType,size_t Order>
dimension<RealType,Order>& dimension<RealType,Order>::set_root(const root_type& root)
{
if constexpr (is_dimension<RealType>::value)
v.front().set_root(root);
else
v.front() = root;
return *this;
}
#endif
// Standard Library Support Requirements
template<typename RealType,size_t Order>
dimension<RealType,Order> fabs(const dimension<RealType,Order>& cr)
{
const typename dimension<RealType,Order>::root_type zero{0};
return zero < cr ? cr
: cr < zero ? -cr
: cr == zero ? dimension<RealType,Order>() // Canonical fabs'(0) = 0.
: cr; // Propagate NaN.
}
template<typename RealType,size_t Order>
dimension<RealType,Order> abs(const dimension<RealType,Order>& cr)
{
return fabs(cr);
}
template<typename RealType,size_t Order>
dimension<RealType,Order> ceil(const dimension<RealType,Order>& cr)
{
using std::ceil;
return dimension<RealType,Order>{ceil(static_cast<typename dimension<RealType,Order>::root_type>(cr))};
}
template<typename RealType,size_t Order>
dimension<RealType,Order> floor(const dimension<RealType,Order>& cr)
{
using std::floor;
return dimension<RealType,Order>{floor(static_cast<typename dimension<RealType,Order>::root_type>(cr))};
}
template<typename RealType,size_t Order>
dimension<RealType,Order> exp(const dimension<RealType,Order>& cr)
{
using std::exp;
using root_type = typename dimension<RealType,Order>::root_type;
const root_type d0 = exp(static_cast<root_type>(cr));
return cr.apply_with_horner([&d0](size_t) { return d0; });
}
template<typename RealType,size_t Order>
dimension<RealType,Order> pow(const dimension<RealType,Order>& x,const typename dimension<RealType,Order>::root_type& y)
{
using std::pow;
using root_type = typename dimension<RealType,Order>::root_type;
constexpr size_t order = dimension<RealType,Order>::order_sum();
std::array<root_type,order+1> derivatives; // array of derivatives
const root_type x0 = static_cast<root_type>(x);
size_t i = 0;
root_type coef = 1;
for (; i<=order && coef!=0 ; ++i)
{
derivatives[i] = coef * pow(x0, y-i);
coef *= y - i;
}
return x.apply([&derivatives,i](size_t j) { return j < i ? derivatives[j] : 0; });
}
template<typename RealType,size_t Order>
dimension<RealType,Order> pow(const typename dimension<RealType,Order>::root_type& x,const dimension<RealType,Order>& y)
{
using std::log;
return exp(y*log(x));
}
template<typename RealType1,size_t Order1,typename RealType2,size_t Order2>
promote<dimension<RealType1,Order1>,dimension<RealType2,Order2>>
pow(const dimension<RealType1,Order1>& x, const dimension<RealType2,Order2>& y)
{
return exp(y*log(x));
}
template<typename RealType,size_t Order>
dimension<RealType,Order> sqrt(const dimension<RealType,Order>& cr)
{
return pow(cr,0.5);
}
// Natural logarithm. If cr==0 then derivative(i) may have nans due to nans from inverse().
template<typename RealType,size_t Order>
dimension<RealType,Order> log(const dimension<RealType,Order>& cr)
{
using std::log;
using root_type = typename dimension<RealType,Order>::root_type;
constexpr size_t order = dimension<RealType,Order>::order_sum();
const root_type d0 = log(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)
return dimension<RealType,0>(d0);
else
{
const auto d1 = dimension<root_type,order-1>(static_cast<root_type>(cr)).inverse(); // log'(x) = 1 / x
return cr.apply_with_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });
}
}
template<typename RealType,size_t Order>
dimension<RealType,Order> frexp(const dimension<RealType,Order>& cr, int* exp)
{
using std::exp2;
using std::frexp;
using root_type = typename dimension<RealType,Order>::root_type;
frexp(static_cast<root_type>(cr), exp);
return cr * exp2(-*exp);
}
template<typename RealType,size_t Order>
dimension<RealType,Order> ldexp(const dimension<RealType,Order>& cr, int exp)
{
using std::exp2;
return cr * exp2(exp);
}
template<typename RealType,size_t Order>
dimension<RealType,Order> cos(const dimension<RealType,Order>& cr)
{
using std::cos;
using std::sin;
using root_type = typename dimension<RealType,Order>::root_type;
const root_type d0 = cos(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (dimension<RealType,Order>::order_sum() == 0)
return dimension<RealType,0>(d0);
else
{
const root_type d1 = -sin(static_cast<root_type>(cr));
const root_type derivatives[] { d0, d1, -d0, -d1 };
return cr.apply_with_horner([&derivatives](size_t i) { return derivatives[i&3]; });
}
}
template<typename RealType,size_t Order>
dimension<RealType,Order> sin(const dimension<RealType,Order>& cr)
{
using std::sin;
using std::cos;
using root_type = typename dimension<RealType,Order>::root_type;
const root_type d0 = sin(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (dimension<RealType,Order>::order_sum() == 0)
return dimension<RealType,0>(d0);
else
{
const root_type d1 = cos(static_cast<root_type>(cr));
const root_type derivatives[] { d0, d1, -d0, -d1 };
return cr.apply_with_horner([&derivatives](size_t i) { return derivatives[i&3]; });
}
}
template<typename RealType,size_t Order>
dimension<RealType,Order> asin(const dimension<RealType,Order>& cr)
{
using std::asin;
using root_type = typename dimension<RealType,Order>::root_type;
constexpr size_t order = dimension<RealType,Order>::order_sum();
const root_type d0 = asin(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)
return dimension<RealType,0>(d0);
else
{
auto d1 = dimension<root_type,order-1>(static_cast<root_type>(cr)); // asin'(x) = 1 / sqrt(1-x*x).
d1 = sqrt(1-(d1*=d1)).inverse(); // asin(1): d1 = depth(1)(inf,inf,-nan,-nan,-nan)
//d1 = sqrt((1-(d1*=d1)).inverse()); // asin(1): d1 = depth(1)(inf,-nan,-nan,-nan,-nan)
return cr.apply_with_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });
}
}
template<typename RealType,size_t Order>
dimension<RealType,Order> tan(const dimension<RealType,Order>& cr)
{
return sin(cr) / cos(cr);
}
template<typename RealType,size_t Order>
dimension<RealType,Order> atan(const dimension<RealType,Order>& cr)
{
using std::atan;
using root_type = typename dimension<RealType,Order>::root_type;
constexpr size_t order = dimension<RealType,Order>::order_sum();
const root_type d0 = atan(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)
return dimension<RealType,0>(d0);
else
{
auto d1 = dimension<root_type,order-1>(static_cast<root_type>(cr));
d1 = ((d1*=d1)+=1).inverse(); // atan'(x) = 1 / (x*x+1).
return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });
}
}
template<typename RealType,size_t Order>
dimension<RealType,Order>
fmod(const dimension<RealType,Order>& cr, const typename dimension<RealType,Order>::root_type& ca)
{
using std::fmod;
using root_type = typename dimension<RealType,Order>::root_type;
return dimension<RealType,Order>(cr).set_root(0) += fmod(static_cast<root_type>(cr), ca);
}
template<typename RealType,size_t Order>
dimension<RealType,Order> round(const dimension<RealType,Order>& cr)
{
using std::round;
return dimension<RealType,Order>{round(static_cast<typename dimension<RealType,Order>::root_type>(cr))};
}
template<typename RealType,size_t Order>
int iround(const dimension<RealType,Order>& cr)
{
using boost::math::iround;
return iround(static_cast<typename dimension<RealType,Order>::root_type>(cr));
}
template<typename RealType,size_t Order>
dimension<RealType,Order> trunc(const dimension<RealType,Order>& cr)
{
using std::trunc;
return dimension<RealType,Order>{trunc(static_cast<typename dimension<RealType,Order>::root_type>(cr))};
}
template<typename RealType,size_t Order>
int itrunc(const dimension<RealType,Order>& cr)
{
using boost::math::itrunc;
return itrunc(static_cast<typename dimension<RealType,Order>::root_type>(cr));
}
template<typename RealType,size_t Order>
std::ostream& operator<<(std::ostream& out, const dimension<RealType,Order>& dim)
{
const std::streamsize original_precision = out.precision();
out.precision(std::numeric_limits<typename dimension<RealType,Order>::root_type>::digits10);
out << "depth(" << dim.depth() << ')';
for (size_t i=0 ; i<dim.v.size() ; ++i)
out << (i?',':'(') << dim.v[i];
out.precision(original_precision);
return out << ')';
}
// Additional functions
template<typename RealType,size_t Order>
dimension<RealType,Order> acos(const dimension<RealType,Order>& cr)
{
using std::acos;
using root_type = typename dimension<RealType,Order>::root_type;
constexpr size_t order = dimension<RealType,Order>::order_sum();
const root_type d0 = acos(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)
return dimension<RealType,0>(d0);
else
{
auto d1 = dimension<root_type,order-1>(static_cast<root_type>(cr));
d1 = -sqrt(1-(d1*=d1)).inverse(); // acos'(x) = -1 / sqrt(1-x*x).
return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });
}
}
template<typename RealType,size_t Order>
dimension<RealType,Order> erfc(const dimension<RealType,Order>& cr)
{
using std::erfc;
using root_type = typename dimension<RealType,Order>::root_type;
constexpr size_t order = dimension<RealType,Order>::order_sum();
const root_type d0 = erfc(static_cast<root_type>(cr));
if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)
return dimension<RealType,0>(d0);
else
{
auto d1 = dimension<root_type,order-1>(static_cast<root_type>(cr));
d1 = -2*boost::math::constants::one_div_root_pi<root_type>()*exp(-(d1*=d1)); // erfc'(x)=-2/sqrt(pi)*exp(-x*x)
return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });
}
}
template<typename RealType,size_t Order>
long lround(const dimension<RealType,Order>& cr)
{
using std::lround;
return lround(static_cast<typename dimension<RealType,Order>::root_type>(cr));
}
template<typename RealType,size_t Order>
long long llround(const dimension<RealType,Order>& cr)
{
using std::llround;
return llround(static_cast<typename dimension<RealType,Order>::root_type>(cr));
}
template<typename RealType,size_t Order>
long double truncl(const dimension<RealType,Order>& cr)
{
using std::truncl;
return truncl(static_cast<typename dimension<RealType,Order>::root_type>(cr));
}
} } } } } // namespace boost::math::differentiation::autodiff::v1
namespace std {
/// boost::math::tools::digits<RealType>() is handled by this std::numeric_limits<> specialization,
/// and similarly for max_value, min_value, log_max_value, log_min_value, and epsilon.
template <typename RealType,size_t Order>
class numeric_limits<boost::math::differentiation::autodiff::dimension<RealType,Order>>
: public numeric_limits<typename boost::math::differentiation::autodiff::dimension<RealType,Order>::root_type>
{ };
} // namespace std
namespace boost { namespace math { namespace tools {
// See boost/math/tools/promotion.hpp
template <typename RealType0,size_t Order0,typename RealType1,size_t Order1>
struct promote_args_2<differentiation::autodiff::dimension<RealType0,Order0>,differentiation::autodiff::dimension<RealType1,Order1>>
{
using type = differentiation::autodiff::dimension<typename promote_args_2<RealType0,RealType1>::type,
#ifndef BOOST_NO_CXX14_CONSTEXPR
std::max(Order0,Order1)>;
#else
Order0 < Order1 ? Order1 : Order0>;
#endif
};
template <typename RealType0,size_t Order0,typename RealType1>
struct promote_args_2<differentiation::autodiff::dimension<RealType0,Order0>,RealType1>
{
using type = differentiation::autodiff::dimension<typename promote_args_2<RealType0,RealType1>::type,Order0>;
};
template <typename RealType0,typename RealType1,size_t Order1>
struct promote_args_2<RealType0,differentiation::autodiff::dimension<RealType1,Order1>>
{
using type = differentiation::autodiff::dimension<typename promote_args_2<RealType0,RealType1>::type,Order1>;
};
} } } // namespace boost::math::tools
#ifdef BOOST_NO_CXX17_IF_CONSTEXPR
#include "autodiff_cpp11.hpp"
#endif
#endif // BOOST_MATH_AUTODIFF_HPP
</code></pre>
<p>It was originally written in C++17, as there is a fair amount of compile-time calculation and the <code>if constexpr</code> feature in particular allows logic to stay together that prior C++ versions unnaturally forced into separate functions/structs. C++11 compatibility was augmented for wider use, however MSVC 2015 is not supported due its difficulty in compiling complex static constexpr class methods.</p>
<p>Here is example usage in calculating derivatives of <span class="math-container">\$f(x)=x^4\$</span>:</p>
<pre><code>#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
template<typename T>
T fourth_power(T x)
{
x *= x;
return x *= x;
}
int main()
{
using namespace boost::math::differentiation;
constexpr int Order=5; // The highest order derivative to be calculated.
const autodiff::variable<double,Order> x(2.0); // Find derivatives at x=2.
const autodiff::variable<double,Order> y = fourth_power(x);
for (int i=0 ; i<=Order ; ++i)
std::cout << "y.derivative("<<i<<") = " << y.derivative(i) << std::endl;
return 0;
}
/*
Output:
y.derivative(0) = 16
y.derivative(1) = 32
y.derivative(2) = 48
y.derivative(3) = 48
y.derivative(4) = 24
y.derivative(5) = 0
*/
</code></pre>
<p>Full documentation: <a href="http://www.unitytechgroup.com/doc/autodiff/" rel="nofollow noreferrer">http://www.unitytechgroup.com/doc/autodiff/</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T01:32:07.177",
"Id": "493993",
"Score": "0",
"body": "Hi Matt. Was wondering if the autodiff library is compatible with std::complex<double> have posted a question here https://stackoverflow.com/questions/64492633/automatic-differentiation-of-functions-of-complex-variables. If so an example would be great. Thanks"
}
] | [
{
"body": "<p>Does <code>RealType</code> have to be a type of floating point number (at least at the root level)? If so, perhaps this should be enforced using <code>std::is_floating_point</code>, with <code>std::enable_if</code> or a <code>static_assert</code>. If not, a different name might be more appropriate.</p>\n\n<hr>\n\n<p>Use <code>std::size_t</code> not <code>size_t</code> (perhaps this is already being done by <code>boost</code> somewhere - it's hard to tell).</p>\n\n<hr>\n\n<p>Templates that aren't supposed to be user facing (e.g. <code>promote</code>, <code>root_type_finder</code>, <code>type_at</code> etc.) could be in a <code>detail</code> namespace.</p>\n\n<p>The template meta-functions may be better named in a similar way to functions, e.g. <code>make_nested_dimensions</code>, <code>get_root_type</code>, <code>get_type_at</code>.</p>\n\n<p>The template specializations are a fundamental part of how the meta-functions work, so it would be nice if they were kept together. I'd only split the definitions up when adding specializations for lots of different classes, which isn't the case here.</p>\n\n<p>Should <code>type_at<double, 5>::type;</code> compile? Perhaps we want something more like:</p>\n\n<pre><code>template<typename T, size_t Depth>\nstruct type_at;\n\ntemplate<typename T>\nstruct type_at<T, 0> { using type = T; };\n\ntemplate<typename RealType, size_t Order, size_t Depth>\nstruct type_at<dimension<RealType, Order>, Depth> { using type = typename type_at<RealType, Depth - 1>::type; };\n</code></pre>\n\n<hr>\n\n<ul>\n<li><p>Readability: Inside a template class, we can omit the template arguments, i.e.: <code>dimension<RealType, Order></code> can be written simply as <code>dimension</code>.</p></li>\n<li><p>Readability: Please add a space between template arguments.</p></li>\n<li><p>Readability: Don't add comments that simply repeat the code, e.g.:</p>\n\n<pre><code>// RealType(cr) | RealType | RealType is copy constructible.\n...\n// r += ca | RealType& | Adds ar to r.\n...\n// r -= cr | RealType& | Subtracts cr from r.\n...\n// r -= ca | RealType& | Subtracts ca from r.\n</code></pre>\n\n<p>etc. Leaving a blank line between the function definitions will make the code itself more readable.</p></li>\n<li><p>Readability: Add the variable names to the function declarations, instead of putting in a comment.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>// Be aware of implicit casting from one dimension<> type to another by this copy constructor.\ntemplate<typename RealType2, size_t Order2>\ndimension<RealType, Order>(const dimension<RealType2, Order2>&);\n</code></pre>\n\n<p>Noooooooooope. * <em>users flee in terror</em> *</p>\n\n<p>(Unless there's some extraordinarily good reason for this, please make it <code>explicit</code>. User code will be clearer and contain fewer bugs.)</p>\n\n<hr>\n\n<p>It would be nice to more clearly separate <code>Order</code> from the size of the <code>std::array</code>. Remembering to add <code>1</code> to <code>Order</code> when accessing the array is error prone, and produces more complicated and surprising code.</p>\n\n<p>We can either use the <code>std::array<T>::size()</code> function or add a static constant size variable to the <code>dimension</code> class.</p>\n\n<hr>\n\n<p>I'd be tempted to add some sort of index or coordinate type for use with <code>at()</code> and <code>derivative()</code>, rather than exposing the user directly to the template parameter pack. e.g.:</p>\n\n<pre><code>template<std::size_t Order>\nstruct indices\n{\n std::array<std::size_t, Order> indices;\n};\n</code></pre>\n\n<p>It's much easier to manipulate or store indices in this form.</p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T23:00:54.723",
"Id": "408982",
"Score": "0",
"body": "Thank you, this is very much appreciated. If you don't mind I would like to respond to some of your questions/points over the next week or so as I digest and incorporate your suggestions. This will not be intended to refute anything you have said, but rather to offer my thoughts for further feedback, should you be inclined to offer it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:32:25.253",
"Id": "409013",
"Score": "0",
"body": "Sure. I'm not familiar enough with the math to give feedback on the implementation / overall design, so these are fairly general C++ comments."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T11:59:49.850",
"Id": "211473",
"ParentId": "211441",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "211473",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-13T22:33:50.910",
"Id": "211441",
"Score": "4",
"Tags": [
"c++",
"mathematics",
"c++17",
"boost"
],
"Title": "Automatic Differentiation with C++ Header-Only Library"
} | 211441 |
<p>I'm trying to implement equality for all types that share same base.</p>
<p>Consider <code>std::vector<unique_ptr<Shape>></code> and that we want to check if a certain given <code>Shape&</code> is <em>equal</em> to a certain shape managed in the vector. The idea is to have a generic solution through a base class, without relying on the exact content of the derived classes and without narrowing it to shapes (which is merely just a usage example).</p>
<p>I came to the following solution, with <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">CRTP</a> and would appreciate comments.</p>
<p><a href="http://coliru.stacked-crooked.com/a/17f786455c192ab9" rel="nofollow noreferrer">Code</a></p>
<h2>AbstractBase</h2>
<pre><code>class AbstractBase {
virtual bool base_equals(const AbstractBase& other) const = 0;
virtual std::ostream& print(std::ostream& out = std::cout) const = 0;
public:
bool operator==(const AbstractBase& other)const {
if(typeid(*this)==typeid(other)) {
return this->base_equals(other);
}
return false;
}
friend std::ostream& operator<<(std::ostream& out, const AbstractBase& ab) {
out << "[" << (void*)&ab << "] ";
return ab.print(out);
}
};
</code></pre>
<h2>CRTP Base</h2>
<pre><code>template<class ActualType>
class Base: public AbstractBase {
virtual bool base_equals(const AbstractBase& other)const override final {
return static_cast<const ActualType&>(*this)
== static_cast<const ActualType&>(other);
}
};
</code></pre>
<h2>Actual Classes</h2>
<pre><code>class A: public Base<A> {
int num;
virtual std::ostream& print(std::ostream& out = std::cout) const {
return out << num;
}
public:
A(int i = 42): num(i) {}
bool operator==(const A& a)const {
return num == a.num;
}
};
class B: public Base<B> {
std::string str;
virtual std::ostream& print(std::ostream& out = std::cout) const {
return out << str;
}
public:
B(const std::string& s = "hello"): str(s) {}
bool operator==(const B& b)const {
return str == b.str;
}
};
</code></pre>
<h2>Simple Usage Example <em>(Test)</em></h2>
<pre><code>int main() {
A a1, a2, a3 = 5;
B b1, b2, b3 = {"bye"};
std::vector<const AbstractBase*> arr = {&a1, &a2, &a3, &b1, &b2, &b3};
for(auto v1: arr) {
for(auto v2: arr) {
std::cout << *v1 << " == " << *v2 << " ? "
<< std::boolalpha << (*v1 == *v2) << std::endl;
}
}
}
</code></pre>
<h2>Output</h2>
<pre class="lang-none prettyprint-override"><code>[0x7ffefdb7f0b0] 42 == [0x7ffefdb7f0b0] 42 ? true
[0x7ffefdb7f0b0] 42 == [0x7ffefdb7f0c0] 42 ? true
[0x7ffefdb7f0b0] 42 == [0x7ffefdb7f0d0] 5 ? false
[0x7ffefdb7f0b0] 42 == [0x7ffefdb7f0e0] hello ? false
[0x7ffefdb7f0b0] 42 == [0x7ffefdb7f110] hello ? false
[0x7ffefdb7f0b0] 42 == [0x7ffefdb7f140] bye ? false
[0x7ffefdb7f0c0] 42 == [0x7ffefdb7f0b0] 42 ? true
[0x7ffefdb7f0c0] 42 == [0x7ffefdb7f0c0] 42 ? true
[0x7ffefdb7f0c0] 42 == [0x7ffefdb7f0d0] 5 ? false
[0x7ffefdb7f0c0] 42 == [0x7ffefdb7f0e0] hello ? false
[0x7ffefdb7f0c0] 42 == [0x7ffefdb7f110] hello ? false
[0x7ffefdb7f0c0] 42 == [0x7ffefdb7f140] bye ? false
[0x7ffefdb7f0d0] 5 == [0x7ffefdb7f0b0] 42 ? false
[0x7ffefdb7f0d0] 5 == [0x7ffefdb7f0c0] 42 ? false
[0x7ffefdb7f0d0] 5 == [0x7ffefdb7f0d0] 5 ? true
[0x7ffefdb7f0d0] 5 == [0x7ffefdb7f0e0] hello ? false
[0x7ffefdb7f0d0] 5 == [0x7ffefdb7f110] hello ? false
[0x7ffefdb7f0d0] 5 == [0x7ffefdb7f140] bye ? false
[0x7ffefdb7f0e0] hello == [0x7ffefdb7f0b0] 42 ? false
[0x7ffefdb7f0e0] hello == [0x7ffefdb7f0c0] 42 ? false
[0x7ffefdb7f0e0] hello == [0x7ffefdb7f0d0] 5 ? false
[0x7ffefdb7f0e0] hello == [0x7ffefdb7f0e0] hello ? true
[0x7ffefdb7f0e0] hello == [0x7ffefdb7f110] hello ? true
[0x7ffefdb7f0e0] hello == [0x7ffefdb7f140] bye ? false
[0x7ffefdb7f110] hello == [0x7ffefdb7f0b0] 42 ? false
[0x7ffefdb7f110] hello == [0x7ffefdb7f0c0] 42 ? false
[0x7ffefdb7f110] hello == [0x7ffefdb7f0d0] 5 ? false
[0x7ffefdb7f110] hello == [0x7ffefdb7f0e0] hello ? true
[0x7ffefdb7f110] hello == [0x7ffefdb7f110] hello ? true
[0x7ffefdb7f110] hello == [0x7ffefdb7f140] bye ? false
[0x7ffefdb7f140] bye == [0x7ffefdb7f0b0] 42 ? false
[0x7ffefdb7f140] bye == [0x7ffefdb7f0c0] 42 ? false
[0x7ffefdb7f140] bye == [0x7ffefdb7f0d0] 5 ? false
[0x7ffefdb7f140] bye == [0x7ffefdb7f0e0] hello ? false
[0x7ffefdb7f140] bye == [0x7ffefdb7f110] hello ? false
[0x7ffefdb7f140] bye == [0x7ffefdb7f140] bye ? true
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:03:18.923",
"Id": "408951",
"Score": "1",
"body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:06:53.857",
"Id": "408952",
"Score": "0",
"body": "The change comes with an \"Edit\" note that makes sure the reader follows + gives credit to the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T11:24:20.663",
"Id": "409024",
"Score": "0",
"body": "On hold as off topic? Not an intuitive use case?? -- Consider `std::vector<unique_ptr<Shape>>` and we want to check if a certain given `Shape&` is equal to a certain shape managed in the vector."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:52:20.593",
"Id": "409233",
"Score": "1",
"body": "[This question is being discussed on meta](https://codereview.meta.stackexchange.com/q/9058/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T23:28:34.183",
"Id": "409281",
"Score": "2",
"body": "\"Edit\" notes still violate [site policy](/help/someone-answers). This is Code Review, not Collaborative Coding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T07:25:24.870",
"Id": "409303",
"Score": "0",
"body": "@AmirKirsh: you scenario (finding a shape in a vector of shapes) still has no defined meaning. In a polymorphic context, you would expect a `Rectangle` with equal sides to be equal to a `Square` of the same size, but your code would differentiate them. Inheritance is meaningful only in a context when you don't have to care / to know if you're dealing with the base or the derived class (see https://en.wikipedia.org/wiki/Liskov_substitution_principle). 1/2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T07:29:34.537",
"Id": "409305",
"Score": "0",
"body": "@AmirKirsh Moreover, in this case, you know the type you're looking for beforehand, so using CRTP to keep track of it is useless. For instance: `std::find_if(first, last, [&shape_to_find](const Shape& s) { using T = std::decay_t<decltype(shape_to_find)>; compatible_type_ptr = dynamic_cast<T*>(&s); if (ptr && *ptr == shape_to_find) return true; return false; });` (2/2)"
}
] | [
{
"body": "<p>I apologize if I'm misunderstanding the problem your solving. If you're merely trying to first determine if two types are subclasses of a third, would it be possible to use avoid mixing an abstract base class and CRTP in favor of an operator overload like this? If so, you can get rid of the CRTP and the AbstractBase::base_equals method.</p>\n\n<pre><code>template< typename T, typename U >\nbool operator==(T&& lhs, U&& rhs) { \n return std::addressof(std::forward< T >(lhs)) == std::addressof(std::forward< U >(rhs)) ||\n std::is_base_of< AbstractBase, T >::value && std::is_base_of< AbstractBase, U >::value;\n}\n</code></pre>\n\n<p><strong>In Response to Original Poster's Reply</strong></p>\n\n<p>My earlier suggestion was simply (but not clearly stated) that you might pick either dynamic polymorphism or parametric polymorphism (not both). Also, I'm checking the memory addresses of objects to as a simple check of equality (to answer part of your reply).</p>\n\n<p>Below is a solution I would use (using CRTP due to the different return types of getValue(); you could use dynamic polymorphism and achieve the same using operator<<). The hiccup is that you can no longer use std::vector, since you have pointers to both <code>BaseTemplate<A>*</code> and <code>BaseTemplate<B>*</code>, so you would need a heterogenous container in your driver code (ie std::tuple or the like). </p>\n\n<p>Per the requirements in your reply, type/memory/value equality are checked with the free overloaded equality operators (you may need to decay the types if const/volatile cause types that fit your definition of equality don't bind to the correct operator== overload). </p>\n\n<pre><code>#include <iostream>\n#include <type_traits>\n\ntemplate <typename Derived> class BaseTemplate {\n std::ostream &print(std::ostream &out) const {\n return static_cast<const Derived *>(this)->print(out);\n }\n\npublic:\n const auto &getValue() const {\n return static_cast<const Derived *>(this)->getValue();\n }\n friend std::ostream &operator<<(std::ostream &out,\n const BaseTemplate<Derived> &rhs) {\n return out << \"[\" << (void *)&rhs << \"] \" << rhs.getValue();\n }\n auto operator*() const { return *static_cast<const Derived *>(this); }\n};\n\nclass A : public BaseTemplate<A> {\n int num;\n\npublic:\n A(int i = 42) : num(i) {}\n const int &getValue() const { return num; }\n bool operator==(const A &a) const { return num == a.num; }\n};\n\nclass B : public BaseTemplate<B> {\n std::string str;\n\npublic:\n B(const std::string &s = \"hello\") : str(s) {}\n const std::string &getValue() const { return str; }\n bool operator==(const B &b) const { return str == b.str; }\n};\n\ntemplate <typename T, typename U> bool operator==(const T &lhs, const U &rhs) {\n return false;\n}\n\ntemplate <typename T> bool operator==(const T &lhs, const T &rhs) {\n return std::addressof(lhs) == std::addressof(rhs) || lhs == rhs;\n}\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:43:15.210",
"Id": "408869",
"Score": "0",
"body": "there are two needs: (a) to check that the type is identical; (b) to check that the value is equal. Note that the required equality is for value and not for address. @Kedar - your proposed code does (a) but doesn't do (b). The CRTP in my original code is for (b). How would you do (b)? Do you have a version without CRTP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T19:01:42.000",
"Id": "408965",
"Score": "0",
"body": "Might be that you have an infinite recursion in your new solution? Operator == calling itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T02:26:43.603",
"Id": "408989",
"Score": "0",
"body": "It didn’t happen when I tested it, but to be sure, you can change the lhs == rhs (within the method) to lhs.getValue() == rhs.getValue()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T04:30:53.130",
"Id": "408996",
"Score": "0",
"body": "Interesting that it didn't recurse for you. Did you test it by actually running the code? Can you share a link to the code? And for the alternative of calling getValue() does it mean that any type has this method? Does it mean that your solution is mainly for types with single value that implements the method getValue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T06:22:09.763",
"Id": "408999",
"Score": "0",
"body": "I did run the code. Your point is valid; I should do the value comparison with (lhs|rhs).getValue(); it’s safer and is part of your requirement anyway. All parameter types of BaseTemplate should have getValue(), though the code above actually doesn’t enforce it properly (since I overloaded operator*, which yields a const reference to an instance of BaseTemplate parameter type). If by your question about whether the solution is for single types, it’s for determining if types are the same, and if so, if they hold the same value). Non-matching types hit the other overload (which yields false)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T06:35:18.073",
"Id": "409000",
"Score": "0",
"body": "The code is from above. I adapted the driver code to test type comparisons. http://coliru.stacked-crooked.com/a/9cf6f3a7addbe271"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T06:52:40.070",
"Id": "409001",
"Score": "0",
"body": "your code never goes to `template <typename T> bool operator==(const T &lhs, const T &rhs)` so it's not clear how it is supposed to be used. Still, if it would go there - it will be an infinite recursion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:01:48.593",
"Id": "409003",
"Score": "0",
"body": "Yes, you're correct. I corrected it in the following link; I removed the overloads from within the classes (so equality is handled generically): http://coliru.stacked-crooked.com/a/3e295fcd5cc27bb5"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T04:24:47.690",
"Id": "211452",
"ParentId": "211445",
"Score": "-2"
}
},
{
"body": "<p>First and foremost, I believe that your fundamental concept is flawed. Equality has a well defined meaning between objects of the same type, or between types themselves, but not in this hybrid scenario. For instance, let's say I have a <code>class C</code>, which inherits from <code>A</code> as well as from <code>Base<C></code>, how shall I compare an instance of <code>A</code> and an instance of <code>C</code>? You would normally expect them to be comparable in a polymorphic context, at least if <code>A</code> implements <code>operator==</code>, wouldn't you? But their <code>type_info</code> is different. You could try and work around that problem by using <code>dynamic_cast</code>, but then I suspect that, given <code>A a; C c;</code>, <code>a == c</code> and <code>c == a</code> wouldn't return the same result, which is unexpected.</p>\n\n<p>I suspect it's a kind of work-around you devised because you had a lot of vaguely related objects bunched together and realized afterwards you had to discriminate between them according to their concrete type.</p>\n\n<p>But it would be best to improve on your overall design (that you can submit here, by the way), rather than persisting in the original one. Because what's the limit? Why not ordering objects of different types when you're at it? A common task when you have equality-comparable objects is to remove duplicates: you'll need to sort the objects to do it efficiently, meaning you have to implement <code>operator<</code> as well.</p>\n\n<p>If you stick to your concept, though:</p>\n\n<ul>\n<li><p>Your base class lacks a virtual destructor. Any base class that will be used as a polymorphic handle needs a virtual destructor, or it might lead to resources leak (see <a href=\"https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors\">this</a>). </p></li>\n<li><p>The virtual <code>print</code> function clearly isn't in the right place (there's no conceptual link between equality and printability), but I suspect it's there only for the purpose of debugging.</p></li>\n<li><p>The code seems to be over-engineered. The only thing your CRTP base class does is a static down-cast, which could be a nice (static polymorphism) if the <code>base_equals</code> method wasn't called after already having performed run-time type identification. It's simpler to directly <code>dynamic_cast</code> your pointers.</p></li>\n</ul>\n\n<p>For instance:</p>\n\n<pre><code>class Base {\n public:\n virtual bool operator==(const Base&) =0;\n virtual ~Base() = default;\n};\n\ntemplate <typename T>\nclass CRTP : public Base{\n virtual bool operator==(const Base& o) const override final {\n auto same_type = dynamic_cast<const T*>(&o);\n return same_type && static_cast<const T&>(*this) == *same_type;\n }\n};\n</code></pre>\n\n<ul>\n<li>there's a balance issue in your code, because it will accept to compare objects of different derived types not implementing the equality operator, but will refuse to compare objects of the same type if it doesn't implement it. To remedy that issue you can check through SFINAE or concepts (C++20) if equality comparison is implemented. Or you can make a different trade-off and skip the CRTP step:</li>\n</ul>\n\n<p>For instance:</p>\n\n<pre><code>class Base {\n public:\n virtual bool operator==(const Base& o) const { return this == &o; }\n virtual ~Base() = default;\n};\n\nclass A : public Base {\n public:\n int i = 4;\n virtual bool operator==(const Base& o) const override final {\n auto same_type = dynamic_cast<const A*>(&o);\n return same_type && i == same_type->i;\n }\n};\n\nclass B : public Base {}; \n</code></pre>\n\n<p>The downside is that you have to implement the down-casting in each derived base class, and the upside that you have a more consistent fall-back scenario for derived classes not implementing an equality operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:12:27.120",
"Id": "408953",
"Score": "0",
"body": "missing virtual dtor - oops - taken ;\n\nchecking same_type with dynamic_cast is wrong it allows equality check between Person and Student on Person's fields -- the check with type_id is the correct way;\n\nprint - it is of course for the sake of the question and not to present any specific design coupling;\n\nvirtual operator== would take you to the derived class so you need to implement the \"same_type\" check in all derived classes... seems better to have non-virtual operator==;"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T11:29:56.363",
"Id": "211469",
"ParentId": "211445",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T01:32:12.930",
"Id": "211445",
"Score": "2",
"Tags": [
"c++",
"polymorphism",
"overloading"
],
"Title": "Polymorphic implementation for == with CRTP"
} | 211445 |
<p>For a little game of mine I have created a Key.h file that should allow representation of a key press combination. A key combination is basically some key represented by its virtual key code stored in <code>int _key</code>and the state of modifier keys - shift, control, alt and windows keys. In case that key combination is used for typing, the key also stores the character that it should produce in <code>_c</code>.</p>
<pre><code>class Key
{
private:
bool _shift;
bool _ctrl;
bool _alt;
bool _win;
int _key;
char _c;
public:
constexpr Key()
:
_shift(),
_ctrl(),
_alt(),
_win(),
_key(),
_c()
{}
constexpr Key(const Key& key)
:
_shift(key._shift),
_ctrl(key._ctrl),
_alt(key._alt),
_win(key._win),
_key(key._key),
_c(key._c)
{}
constexpr Key(bool shift, bool ctrl, bool alt, bool win, int key, char c)
:
_shift(shift),
_ctrl(ctrl),
_alt(alt),
_win(win),
_key(key),
_c(c)
{}
Key& operator= (Key& key)
{
_shift = key._shift;
_ctrl = key._ctrl;
_alt = key._alt;
_win = key._win;
_key = key._key;
_c = key._c;
}
bool operator== (const Key& key) const
{
return (_shift == key._shift && _ctrl == key._ctrl && _alt == key._alt && _win == key._win && _key == key._key, _c == key._c);
}
bool operator!= (const Key& key) const
{
return !(*this == key);
}
};
</code></pre>
<p>Are there any design flaws or some obvious things that I'm missing?</p>
| [] | [
{
"body": "<p><strong>I would start by fixing the warnings, one of which is an actual bug:</strong></p>\n\n<hr>\n\n<p><strong>[1]\nOperator = not returning a value</strong></p>\n\n<pre><code>main.cpp: In member function 'Key& Key::operator=(Key&)':\nmain.cpp:50:5: warning: no return statement in function returning non-void [-Wreturn-type]\n }\n ^\nmain.cpp: In member function 'bool Key::operator==(const Key&) const':\n</code></pre>\n\n<p><strong>Also:</strong> your operator= gets <code>Key& key</code> instead of <code>const Key& key</code></p>\n\n<p><strong>Wait!</strong> don't rush to fix it. You can just eliminate it altogether and rely on the default assignment operator that does the same job (\"rule of zero\").</p>\n\n<hr>\n\n<p><strong>[2] using comma in the long list of equality check -- an actual bug</strong></p>\n\n<pre><code>main.cpp:54:100: warning: left operand of comma operator has no effect [-Wunused-value]\n return ( ... && _win == key._win && _key == key._key, _c == key._c);\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~\n</code></pre>\n\n<p><strong>Wait!</strong> don't rush to fix it. We will use std::bitset so the entire operator== would become simpler.</p>\n\n<hr>\n\n<p>After fixing the warnings above we can proceed for improvements.</p>\n\n<p><strong>[3] Use <code>std::bitset</code> for the bool flags</strong></p>\n\n<p>Instead of:</p>\n\n<pre><code>bool _shift;\nbool _ctrl;\nbool _alt;\nbool _win;\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>enum SpecialKeys {SHIFT, CTRL, ALT, WIN, _SIZE_};\nstd::bitset<SpecialKeys::_SIZE_> specialKeys;\n</code></pre>\n\n<hr>\n\n<p><strong>[4] No need for assignment operator and copy ctor (rule of zero).</strong></p>\n\n<p>Just use the defaults.</p>\n\n<hr>\n\n<p><strong>Proposed fixed code:</strong></p>\n\n<pre><code>#include <bitset>\n\nclass Key {\n enum SpecialKeys {SHIFT, CTRL, ALT, WIN, _SIZE_};\n std::bitset<SpecialKeys::_SIZE_> specialKeys;\n int _key = 0;\n char _c = 0;\npublic:\n constexpr Key() {}\n constexpr Key(bool shift, bool ctrl, bool alt, bool win, int key, char c)\n : _key(key), _c(c)\n {\n specialKeys[SpecialKeys::SHIFT] = shift;\n specialKeys[SpecialKeys::CTRL] = ctrl;\n specialKeys[SpecialKeys::ALT] = alt;\n specialKeys[SpecialKeys::WIN] = win;\n }\n\n bool operator== (const Key& key) const\n {\n return (specialKeys == key.specialKeys && _key == key._key && _c == key._c);\n }\n\n bool operator!= (const Key& key) const\n {\n return !(*this == key);\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T02:26:38.687",
"Id": "408855",
"Score": "0",
"body": "Ah, very constructive. Since you mentioned the rule of zero, should I just completely remove the copy constructor or request it from compiler with `= default` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T02:32:43.380",
"Id": "408856",
"Score": "0",
"body": "Just use the defaults by not declaring at all, no need for `= default` in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T14:57:08.877",
"Id": "408918",
"Score": "0",
"body": "Don't use `_SIZE_` as an identifier in your code - that's [reserved for the implementation for any use](http://eel.is/c++draft/lex.name#3) (so could even be a macro)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:27:46.300",
"Id": "409007",
"Score": "0",
"body": "I like this version more, in the upcoming C++20, you would even be able to default the operator<=>"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T02:16:34.007",
"Id": "211448",
"ParentId": "211446",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211448",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T01:43:53.897",
"Id": "211446",
"Score": "0",
"Tags": [
"c++"
],
"Title": "A class that represents a key combination"
} | 211446 |
<p>I'm given this method, and requested to analyze what it does, and minimize its complexity (both time and space).<br>
All values are known to be larger than zero.</p>
<pre><code>public static boolean search(int[] a, int num) {
for(int i = 0; i < a.length; i++)
for(int j = i; j < a.length; j++) {
int res = 0;
for(int k = i; k <= j; k++)
res += a[k];
if(res == num)
return true;
}
return false;
}
</code></pre>
<p>From what it looks to me it's searching for any series of consecutive numbers in the given array, that sum up to <code>num</code>, with an <em>O(n<sup>3</sup>)</em> complexity.</p>
<p>I've tried to rewrite it like this:</p>
<pre><code>public static boolean search(int[] a, int num) {
for (int i = 0; i < a.length; i++) {
int sum = 0;
for (int j = i; j < a.length; j++) {
sum += a[j];
if (sum == num)
return true;
}
if (num > sum)
break;
}
return false;
}
</code></pre>
<p>Which has a complexity of <img src="https://latex.codecogs.com/png.latex?%5Cinline%20%5Cdpi%7B150%7D%20%5Ctiny%20O%28n%5Ccdot%5Cfrac%7Bn+1%7D%7B2%7D%29" alt=""> (BTW, is there a better way to denote this complexity?).</p>
<p>What other strategies can I take to minimize the complexity even further? Can I reach <em>O(n)</em>?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T08:26:59.060",
"Id": "408873",
"Score": "0",
"body": "I think you can denote the complexity as O(n^2). You can remove constants and n^2 >> n so you can ignore the `+1` part after multiplying"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T08:30:39.807",
"Id": "408874",
"Score": "0",
"body": "Yeah, so I thought. Any way to reduce the complexity to _O(n)_?"
}
] | [
{
"body": "<p>Both the original and your revision have the same problem. They reset <code>sum</code>/<code>res</code> to zero on every iteration and then recalculate it. To avoid this, store the sums in an array. </p>\n\n<pre><code>int[] sums = new int[a.length + 1];\nsums[0] = 0;\nfor (int i = 0; i < a.length; i++) {\n sums[i + 1] = sums[i] + a[i];\n}\n</code></pre>\n\n<p>This takes <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> time to calculate. </p>\n\n<p>For any <code>i</code>, <code>sums[i]</code> is the sum of the first <code>i</code> elements of the array. </p>\n\n<p>Since we know that all values are positive, adding a value always increases the sum. And removing a value decreases it. So how do we use that? Consider </p>\n\n<pre><code>int left = 0;\nint right = 0;\nwhile (right < sums.length) {\n int sum = sums[right] - sums[left];\n if (sum == target) {\n return true;\n }\n\n if (sum > target) {\n // if the sum is too big, reduce it by dropping a value from it\n left++;\n } else {\n // if the sum is too small, increase it by adding a value to it\n right++;\n }\n}\n</code></pre>\n\n<p>I changed the name of <code>num</code> to <code>target</code> as being more descriptive of what it represents. </p>\n\n<p>This uses the sums stored in our array to calculate the sum from <code>left + 1</code> to <code>right</code> in the original array. </p>\n\n<p>On each iteration of the loop, we either return or increment one of the indexes. The worst case is where the sum of the elements before the last is too small but the last element itself is equal to or larger than the target. In that case, we increment <code>right</code> <code>sums.length</code> times and we increment <code>left</code> <code>sums.length</code> times. That's <span class=\"math-container\">\\$2n + 2\\$</span> total, which is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. </p>\n\n<hr>\n\n<p>This takes <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> space as well. If you need constant space, you can skip the first part and track the sum as an integer. See <a href=\"https://codereview.stackexchange.com/a/211465/71574\">here</a>. </p>\n\n<p>If you can't see the deleted answer from <a href=\"https://codereview.stackexchange.com/users/125850/mtj\">mtj</a>, it basically says to do something like </p>\n\n<pre><code>int left = 0;\nint right = 0;\nint sum = 0;\nwhile (right < a.length) {\n if (sum > target) {\n // if the sum is too big, reduce it by dropping a value from it\n sum -= a[left];\n left++;\n } else {\n // if the sum is too small, increase it by adding a value to it\n sum += a[right];\n right++;\n }\n\n if (sum == target) {\n return true;\n }\n}\n\nreturn false;\n</code></pre>\n\n<p>Assumes that <code>target</code> and all the values in <code>a</code> are positive. </p>\n\n<p>You can see a solution to a similar problem <a href=\"https://codereview.stackexchange.com/a/52139/71574\">here</a> as well. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T11:16:53.350",
"Id": "211467",
"ParentId": "211453",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211467",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T05:16:53.107",
"Id": "211453",
"Score": "0",
"Tags": [
"java",
"performance",
"algorithm",
"complexity"
],
"Title": "Searching for a sum of any series in array"
} | 211453 |
<p>Below is my attempt at a doubly-linked list in Python (3):</p>
<pre><code>class LinkedListNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class LinkedList:
def __init__(self):
self.head = self.tail = None
self.size = 0
def get_first(self):
if self.head:
return self.head.value
raise Exception('Reading from an empty list.')
def get_last(self):
if self.tail:
return self.tail.value
raise Exception('Reading from an empty list.')
def add_first(self, value):
node = LinkedListNode(value)
if self.head:
node.right = self.head
self.head.left = node
self.size += 1
else:
self.head = self.tail = LinkedListNode(value)
self.size = 1
def add_last(self, value):
node = LinkedListNode(value)
if self.tail:
node.left = self.tail
self.tail.right = node
self.size += 1
else:
self.head = self.tail = node
self.size = 1
def remove_first(self):
if self.head:
ret = self.head.value
self.head = self.head.right
self.head.left = None
self.size -= 1
return ret
raise Exception('Removing from an empty list.')
def remove_last(self):
if self.tail:
ret = self.tail.value
self.tail = self.tail.left
self.tail.right = None
self.size -= 1
return ret
raise Exception('Removing from an empty list.')
def __repr__(self):
str = '['
if self.size > 0:
str += self.head.value
node = self.head.right
while node:
str += ', ' + node.value
node = node.right
return str + ']'
def main():
list = LinkedList()
while True:
cmd_line = input()
if cmd_line == 'quit':
break
command_tokens = cmd_line.split()
command = command_tokens[0]
try:
if command == "get_first":
print(list.get_first())
elif command == "get_last":
print(list.get_last())
elif command == "add_first":
list.add_first(command_tokens[1])
elif command == "add_last":
list.add_last(command_tokens[1])
elif command == "remove_first":
list.remove_first()
elif command == "remove_last":
list.remove_last()
elif command == "print":
print(list)
except Exception:
print("Unknown command")
main()
</code></pre>
<p>How would I rewrite it in a professional manner? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T21:25:52.397",
"Id": "408978",
"Score": "0",
"body": "Are you sure this is a version you want to review? It has gaping bugs - once the list has a node, neither `self.head` nor `self.tail` is ever updated anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T14:33:37.427",
"Id": "409042",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<h1>A better <code>main</code></h1>\n\n<p><a href=\"https://stackoverflow.com/a/20158605/667648\">Instead of just calling <code>main()</code> at the bottom, wrap it in <code>if __name__ == \"__main__\":</code>.</a> In otherwords:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>This allows me to re-use your module better, see the answer I linked for more details.</p>\n\n<h1><code>if</code> chains</h1>\n\n<p>This portion of code:</p>\n\n<pre><code> if command == \"get_first\":\n print(list.get_first())\n elif command == \"get_last\":\n print(list.get_last())\n elif command == \"add_first\":\n list.add_first(command_tokens[1])\n elif command == \"add_last\":\n list.add_last(command_tokens[1])\n elif command == \"remove_first\":\n list.remove_first()\n elif command == \"remove_last\":\n list.remove_last()\n elif command == \"print\":\n print(list)\n</code></pre>\n\n<p>Is a code smell to me. I would refactor this with a dictionary:</p>\n\n<pre><code>commands = {\n \"get_first\": lambda: print(list.get_first()),\n \"get_last\": lambda: prrint(list.get_last()),\n ...\n}\n</code></pre>\n\n<p>This can then be called with:</p>\n\n<pre><code>commands[command]()\n</code></pre>\n\n<h1>Library Shadowing</h1>\n\n<pre><code>list = LinkedList()\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3.7/tutorial/datastructures.html\" rel=\"nofollow noreferrer\"><code>list</code> is already part of</a> the standard library. I would not over shadow the name. I would change the name to something like <code>linked</code> for instance.</p>\n\n<h1><code>namedtuple</code>?</h1>\n\n<p>It is questionable whether you want to do this or not, but the class <code>LinkedListNode</code> is just an <code>__init__</code> method. In this case, I would usually advocate using a <a href=\"https://docs.python.org/3.7/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> instead and using the <code>defaults</code> parameter added in Python 3.7 if applicable. Although, then again, <code>defaults</code> is only in 3.7... So, maybe not applicable. Still useful to know about.</p>\n\n<h1>Implement <code>__str__</code> how you implemented <code>__repr__</code></h1>\n\n<p><a href=\"https://docs.python.org/3/library/stdtypes.html#str\" rel=\"nofollow noreferrer\"><code>__str__</code> is for human-readable output.</a> <code>__repr__</code> is for more internal information. You have implemented <code>__repr__</code> to display a human readable representation of your list. Switch to <code>__str__</code> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:56:22.127",
"Id": "211460",
"ParentId": "211455",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211460",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T06:28:58.987",
"Id": "211455",
"Score": "0",
"Tags": [
"python",
"linked-list"
],
"Title": "Linked list in Python"
} | 211455 |
<p>I wrote the next code chunk to save all the allowed positions from a 3x3 matrix, it's working but I think it could be better. Besides something similar happens in my Randomizer class, although I admit it's messy.</p>
<pre><code>public class MatrixRegistry : MonoBehaviour
{
private int matrixVolume;
private int matrixCount;
private GameObject[] matrix;
private List<GameObject> dynamicCubes = new List<GameObject>();
private List<Vector3> staticCubes = new List<Vector3>();
private List<Vector3> allowedPositions = new List<Vector3>();
public Func<List<GameObject>> GetDynamicCubes { get; private set; }
public Func<List<Vector3>> GetAllowedPositions { get; private set; }
private void Awake()
{
#region Getting all Matrix Cubes
matrixCount = gameObject.transform.childCount;
if (matrixCount != 0)
{
matrix = new GameObject[matrixCount];
for (int i = 0; i < matrixCount; i++)
{
matrix[i] = gameObject.transform.GetChild(i).gameObject;
if (matrix[i].GetComponent<CubeInfo>().cubeType == CubeSort.Dynamic)
{
dynamicCubes.Add(matrix[i]);
}
if (matrix[i].GetComponent<CubeInfo>().cubeType == CubeSort.Static)
{
staticCubes.Add(matrix[i].transform.position);
}
}
}
GetDynamicCubes = () => dynamicCubes;
#endregion
#region Setting Allowed Positions
matrixVolume = 3; // Hard Coding
for (int x = 0; x < matrixVolume; x++)
{
for (int y = 0; y < matrixVolume; y++)
{
for (int z = 0; z < matrixVolume; z++)
{
Vector3 position = new Vector3
{
x = x,
y = y,
z = z
};
allowedPositions.Add(position);
}
}
}
for (int f = 0; f < staticCubes.Count; f++)
{
for (int a = 0; a < allowedPositions.Count; a++)
{
if (allowedPositions[a] == staticCubes[f])
{
allowedPositions.Remove(allowedPositions[a]);
}
}
}
GetAllowedPositions = () => allowedPositions;
#endregion
}
}
</code></pre>
<hr>
<pre><code>public class Randomizer
{
private MatrixRegistry matrixRegistry;
private EventManager eventManager;
public Randomizer(MatrixRegistry matrixRegistry, EventManager eventManager)
{
this.matrixRegistry = matrixRegistry;
this.eventManager = eventManager;
eventManager.OnStartGame += Randomize;
}
private void Randomize()
{
for (int i = 0; i < matrixRegistry.GetDynamicCubes().Count; i++)
{
Vector3 randomPosition = new Vector3
{
x = Random.Range(0, 3),
y = Random.Range(0, 3),
z = Random.Range(0, 3)
};
for (int j = 0; j < matrixRegistry.GetAllowedPositions().Count; j++)
{
for (int k = 0; k < matrixRegistry.GetDynamicCubes().Count; k++)
{
if (randomPosition == matrixRegistry.GetAllowedPositions()[j])
{
if (randomPosition != matrixRegistry.GetDynamicCubes()[k].transform.position)
{
matrixRegistry.GetDynamicCubes()[i].transform.position = randomPosition;
}
}
}
}
}
}
}
</code></pre>
<p>The randomizer class should check all the allowed positions to get in place all the cubes and avoid overlapping issues.
I know it's not the best, and this is why I'm here.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:24:49.660",
"Id": "408864",
"Score": "0",
"body": "Why don't you post the complete class? I'd be much easier to review it having all the code rather then some _random_ snippets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:39:27.593",
"Id": "408867",
"Score": "1",
"body": "@t3chb0t I didn't think it was necessary, it's just a for loop, but already I did it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:42:12.597",
"Id": "408868",
"Score": "1",
"body": "It looks much better now and it's much easier to understand. Thanks for updating ;-]"
}
] | [
{
"body": "<p>The way you are checking if any allowedPositions are in the staticCubes list seems very inefficient to me. I think it would be more efficient to check whether each position is in the staticCubes list as they are created then add them to the allowedPositions list.</p>\n\n<p>Using a LINQ query for this wil also make it much more concise:</p>\n\n<pre><code>allowedPositions = (from int x in Enumerable.Range(0, matrixVolume)\n from int y in Enumerable.Range(0, matrixVolume)\n from int z in Enumerable.Range(0, matrixVolume)\n let position = new Vector3(x, y, z)\n where !staticCubes.Contains(position)\n select position).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:35:57.897",
"Id": "409015",
"Score": "0",
"body": "I don't know much about LINQ features, I'm going to read about it. About Randomizer class, the Randomize method could be improve using LINQ. I still think is awful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T14:20:30.230",
"Id": "409039",
"Score": "0",
"body": "@LobsangWhite - I added notes about the Randomizer class for you to look at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T17:34:34.873",
"Id": "409071",
"Score": "0",
"body": "Yes, but it's not swap among their own positions, it's a 3x3 matrix, that's means 27 positions, what it does is shuffle among all the possible positions, but the static ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:08:42.563",
"Id": "409076",
"Score": "0",
"body": "@LobsangWhite - according to your code, the positions in dynamicCubes don't include the positions in staticCubes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:18:55.053",
"Id": "409088",
"Score": "0",
"body": "Exactly, this is why I use GetAllowedPositions method, because I stored all the matrix positions there, except static cubes positions, and I check if the new position could be the right one if is equal to an allowed position from the list returned by GetAllowedPositions method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:23:51.643",
"Id": "409090",
"Score": "0",
"body": "@LobsangWhite -- If the dynamicCubes have the same positions as the allowedPositions, then I don't see the difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:45:29.590",
"Id": "409093",
"Score": "0",
"body": "No, they are not, look in MatrixRegistry the way allowed positions, I store all 27 position and then I remove the static positions, maybe, you think the matrix is full of cubes, dynamics and statics, but the matrix have spaces also, where the dynamic cubces moves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:40:59.933",
"Id": "409095",
"Score": "0",
"body": "@LobsangWhite - I made another attempt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T21:18:07.967",
"Id": "409098",
"Score": "0",
"body": "I'm sorry, could be the language barrier, I'm not a native english speaker, either way it doesn't work, they are overlapping each other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:54:15.580",
"Id": "409110",
"Score": "0",
"body": "@LobsangWhite - I would suggest submit a new question for the randomizer class, but this time include what the allowedPositions would look like and what the dynamicCube positions would be before and after the randomizing."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T05:39:22.507",
"Id": "211518",
"ParentId": "211457",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211518",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:10:16.227",
"Id": "211457",
"Score": "3",
"Tags": [
"c#",
"unity3d"
],
"Title": "Saving allowed positions from a 3x3 matrix"
} | 211457 |
<p>I've been experimenting more with webcrawling and hence have started to get a better understanding compared to my previous questions. Right now, my code scraps from a car forum on each page and iterates through every pages. What would you recommend to improve on?</p>
<pre><code>import requests
from bs4 import BeautifulSoup, SoupStrainer
import pandas as pd
list_topic = []
list_time = []
SESSION = requests.Session()
def get_response(url): # Gets the <html> structure from the website #
response = SESSION.get(url)
soup = BeautifulSoup(response.text, 'lxml',
parse_only=SoupStrainer('ul', {'class': 'posts posts-archive'}))
return soup
def iteration(url, max_page=52):
starting_page = 1
while starting_page <= max_page:
## formats the new URL etc (https://paultan.org/topics/test-drive-reviews/page/1) ##
new_url = url + f"page/{starting_page}"
data = get_response(new_url)
get_reviews(data)
## iteration starts ##
starting_page += 1
def get_reviews(response):
for container in response('article'):
title = container.h2.a.text
time = container.time.text
list_topic.append(title)
list_time.append(time)
else:
None
def create_pdReview():
return pd.DataFrame({'Title': list_topic, 'Time': list_time})
if __name__ == '__main__':
URL = 'https://paultan.org/topics/test-drive-reviews/'
print(iteration(URL))
print(create_pdReview())
</code></pre>
<p>I've been wondering; would using <code>yield</code> improve the efficiency and simplicity of the code? How would it be done? Because I've been trying to learn from my previous inquiries that has been answered on earlier. Here is a <a href="https://codereview.stackexchange.com/questions/211238/cleaner-way-of-appending-data-to-list-in-beautifulsoup">similar question</a> and I'm trying to put to practice what has been recommended so far.</p>
| [] | [
{
"body": "<p>When we are discussing performance of a particular piece of code, it's important to recognize bottlenecks and major contributors to the runtime of the program.</p>\n\n<p>In your particular case, even though you've applied some optimizations like <code>SoupStrainer</code> speed-up for HTML parsing, the <em>synchronous nature of the script</em> is the biggest problem by far. The script is processing pages one by one, not getting to the next page until the processing for the current page is finished.</p>\n\n<p>Switching to an asynchronous approach would be the natural next step in your optimizations. Look into using third-party frameworks like <a href=\"https://scrapy.org/\" rel=\"nofollow noreferrer\"><code>Scrapy</code></a> or, if you are adventurous, things like <code>asyncio</code> or <code>grequests</code>. </p>\n\n<hr>\n\n<p>You could apply one more optimization to your current script which should help you optimize the \"crawling/scraping\" part - instead of using <code>requests.get()</code>, initialize <code>session = requests.Session()</code> and use <code>session.get()</code> to make requests (<a href=\"http://docs.python-requests.org/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\">documentation</a>). This would allow the underlying TCP connection to be re-used for subsequent requests resulting in a performance increase.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T02:39:02.767",
"Id": "408990",
"Score": "0",
"body": "I've changed the way of iteration; but it looks like an honest mess at the moment. I've used Session as you've recommended ~ but at the moment I'm trying to think how to simplify and get it to work with my previous version =l."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T04:09:11.677",
"Id": "408995",
"Score": "0",
"body": "@Minial I usually use a class and store `session` as an instance attribute which is initialized in a class constructor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T16:25:55.593",
"Id": "211488",
"ParentId": "211458",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211488",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T07:46:16.080",
"Id": "211458",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"beautifulsoup"
],
"Title": "Webcrawler for a car forum"
} | 211458 |
<p>I have text inside a variable that I need to separate in paragraphs, and at the same time respect the manual breaklines.</p>
<p>This is my code:</p>
<pre><code> {description.split('\n\n').map(paragraph => (
<p>
{paragraph.split('\n').map(
(line, index) =>
index > 0 ? (
<span>
<br />
{line}
</span>
) : (
line
)
)}
</p>
))}
</code></pre>
<p>I am not specially happy with the code. It is not very readable. Any ideas how to improve it?</p>
| [] | [
{
"body": "<p>Two things that help in cases like this (IMHO):</p>\n\n<ul>\n<li>Extract a function for more complex logic or a <code>Array.map</code> callback (e.g. to give a descriptive name and/or avoid nesting) </li>\n<li>Provide descriptive names for non-obvious stuff (e.g. I'd prefer <code>firstLine</code> and <code>remainingLines</code> (or something similar) over using <code>index</code>)</li>\n</ul>\n\n<p>I'd probably do something like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>description.split('\\n\\n').map(renderParagraph)\n\n// If you are in a class, this could be a method on the class\nfunction renderParagraph(paragraph) {\n // With fancy ES6:\n const [firstLine, ...rest] = paragraph.split('\\n')\n // Or ES5:\n const lines = paragraph.split('\\n')\n const firstLine = lines[0]\n const rest = lines.slice(1)\n\n return (\n <p>\n {firstLine}\n {rest.map(line => (\n // React.Fragment doesn’t create a wrapper element in the DOM.\n // If you don’t care about that, you can use div instead\n <React.Fragment>\n <br />\n {line}\n </React.Fragment>\n )}\n </p>\n )\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T13:24:32.033",
"Id": "412920",
"Score": "0",
"body": "This looks very readable. Asking because I don't know, why did you use `React.Fragment`? Is it better than `span`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T13:27:41.920",
"Id": "412921",
"Score": "1",
"body": "OK I read the documentation https://reactjs.org/docs/fragments.html, and fragments are clearly better. Because it avoids extra wrapper elements. Could you please add this part to the answer as well. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T19:46:33.610",
"Id": "412953",
"Score": "1",
"body": "Good suggestion, thanks. I changed the code comment to clarify my preference of React.Fragment"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T00:58:43.730",
"Id": "211511",
"ParentId": "211462",
"Score": "1"
}
},
{
"body": "<p>You almost got it perfectly. </p>\n\n<p>The only bit that could be changed is the part putting <code><br/></code> tags between lines. If you want to build a JSX element by putting nodes between each array string, I would recommend using <code>reduce</code>.</p>\n\n<p>Reduce will iterate over your array starting by the indexes <code>0</code> and <code>1</code>. By outputting an array like the following : <code>[total, <br />, line]</code> you can build up your paragraph :</p>\n\n<pre><code>paragraph.split('\\n').reduce((total, line) => [total, <br />, line])\n</code></pre>\n\n<p>Working example :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna \naliqua.\n\nUt enim ad minim veniam, quis nostrud exercitation \nullamco laboris nisi ut aliquip ex ea commodo consequat.\n\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum \ndolore eu fugiat nulla pariatur.Excepteur sint occaecat cupidatat non proident, \nsunt in culpa qui officia deserunt mollit anim id est laborum`\n\nconst Renderer = () =>\n <div>\n {text.split('\\n\\n').map(paragraph =>\n <p>\n {paragraph.split('\\n').reduce((total, line) => [total, <br />, line])}\n </p>\n )}\n </div>\n\nReactDOM.render(\n <Renderer />,\n document.getElementById('root')\n);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id='root'/></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T09:41:00.317",
"Id": "211531",
"ParentId": "211462",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T09:00:24.593",
"Id": "211462",
"Score": "3",
"Tags": [
"react.js",
"jsx"
],
"Title": "Rendering plain text with paragraphs and line breaks as HTML"
} | 211462 |
<p>You might consider this question a follow-up of:</p>
<p><a href="https://codereview.stackexchange.com/q/211384/104270">BigInteger check in C from a string</a></p>
<p>Although, this time, I used C++.</p>
<p>I am on Linux Mint 19.1 with the compiler version:</p>
<pre class="lang-none prettyprint-override"><code>g++-8 (Ubuntu 8.2.0-1ubuntu2~18.04) 8.2.0
</code></pre>
<p>I tried to push myself hard in C, but it obviously requires one of:</p>
<ul>
<li><p>more skill / experience</p></li>
<li><p>lower-level approach</p></li>
</ul>
<p>or both.</p>
<p>That is why I decided to transition to C++, already bought one C++ online course on Udemy, but back to coding, the current version looks straightforward to me, I see no more pointers, etc., which sounds ideal to me:</p>
<hr>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
//#include <string> // I don't get why it compiles without this header
bool string_contains_integer(std::string str)
/*
This function iterates through an array of chars,
and checks each character to be a digit;
optionally including a starting "+/-" sign.
Returns true if the string contains a number (string of digits);
Returns false if the string contains another character(s).
Starting "+/-" gets ignored, as we accept all integer numbers.
*/
{
// if the string is empty, return right away
if ( str.empty() ) return false;
// I'd like to avoid repeated length() calls
unsigned long long string_length = str.length();
// find out if there is a "+/-" sign
bool sign_present = ( (str[0] == '-') || (str[0] == '+') );
// check if there is the sign only
if ( sign_present && (string_length == 1) ) return false;
// iterate through all characters in the string
for (unsigned long long i = 0; i < string_length; i++)
{
// skip the digit check for the sign at the beginning
if ( (i == 0) && sign_present ) continue;
// this is actually the core part checking on digits
if ( ! std::isdigit( (unsigned char) str[i] ) ) return false;
}
// If we got here, then all the characters are digits,
// possibly starting with a sign.
return true;
}
int main(void)
{
if ( string_contains_integer("-123456789123456789123456789123456789123456789123456789123456789") )
{
std::cout << "PASS: Input is a number.\n";
return 0;
}
else
{
std::cerr << "FAIL: Input is not a number!\n";
return 1;
}
}
</code></pre>
<hr>
<p>This program I compile as follows:</p>
<pre class="lang-none prettyprint-override"><code>g++-8 -std=c++17 -Wall -Wextra -Werror -Wpedantic -pedantic-errors -o bigInteger bigInteger.cpp
</code></pre>
| [] | [
{
"body": "<p>You do need to include <code><string></code>. Your platform seems to bring it in as a side-effect of other includes, but you can't portably rely on that.</p>\n\n<p>If there's no need to modify the contents of the string, prefer to pass by reference, to reduce copying:</p>\n\n<pre><code>bool string_contains_integer(const std::string& str)\n// ^^^^^ ^\n</code></pre>\n\n<p>Instead of looping with indexes, learn to use <em>iterators</em>. If you really must use indexes, use the correct type (<code>std::string::size_type</code>, not <code>unsigned long long</code>).</p>\n\n<p>We don't need to write our own loop by hand, as there's a standard algorithm that will do that for us; we just need to supply the correct predicate function:</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <string>\n\nbool string_contains_integer(const std::string& str)\n/*\n This function iterates through an array of chars,\n and checks each character to be a digit;\n optionally including a starting \"+/-\" sign.\n\n Returns true if the string contains a number (string of digits);\n Returns false if the string contains any other character(s).\n\n Starting \"+/-\" gets ignored, as we accept all integer numbers.\n*/\n{\n auto from = str.begin();\n auto to = str.end();\n\n if (from == to) {\n return false;\n }\n\n if (*from == '+' || *from == '-') {\n ++from;\n }\n\n return from != to\n && std::all_of(from, to,\n [](unsigned char c){ return std::isdigit(c); });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T01:24:22.657",
"Id": "424523",
"Score": "1",
"body": "Or better yet, use a `std::string_view`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T11:57:37.667",
"Id": "211472",
"ParentId": "211470",
"Score": "5"
}
},
{
"body": "<p>In this self-mini-review, let it be clear, I just want to point out several things I do differently now. These were untouched by <a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">Toby Speight</a>, so could be beneficial to someone. All of these are opinion-based!</p>\n\n<h2>Styling points</h2>\n\n<ul>\n<li><p>I add spaces around parentheses now, like in this case:</p>\n\n<pre><code>bool string_contains_integer ( const std::string & str )\n</code></pre></li>\n<li><p>I write clearer function's <em>function</em> comments:</p>\n\n<pre><code>// True : If the string contains an integer number (possibly starting with a sign).\n// False: If the string contains some other character(s).\n</code></pre></li>\n<li><p>I no longer use redundant parentheses, like in this case:</p>\n\n<pre><code>if ( i == 0 && sign_present ) continue;\n</code></pre></li>\n<li><p>I put the function's <em>function</em> comment on top of the function:</p>\n\n<pre><code>// True : If the string contains an integer number (possibly starting with a sign).\n// False: If the string contains some other character(s).\nbool string_contains_integer ( const std::string & str )\n</code></pre>\n\n<p>because I found out there is a helper in <a href=\"https://code.visualstudio.com/\" rel=\"nofollow noreferrer\">Visual Studio Code</a> - if If I hover the mouse over the function call anywhere in the code:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xkx5O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xkx5O.png\" alt=\"Helper in Visual Studio Code\"></a></p></li>\n</ul>\n\n<hr>\n\n<h2>Compilation points</h2>\n\n<p>I use <code>-Wc++11-compat</code> flag to ensure compatibility with old compilers.</p>\n\n<blockquote>\n <p>Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g., identifiers in ISO C++ 1998 that are keywords in ISO C++ 2011. This warning turns on <code>-Wnarrowing</code> and is enabled by <code>-Wall</code>.</p>\n</blockquote>\n\n<p>Even since I use <code>-Wall</code> already, it could be used explicitly in case you for any reason opt to remove <code>-Wall</code>. The compatibility flag could be useful.</p>\n\n<hr>\n\n<h2>Code points</h2>\n\n<p>I no longer call <code>str.empty()</code> as this was basically a redundant call of <code>str.length()</code>:</p>\n\n<pre><code>std::size_t str_length = str.length();\nif ( str_length == 0 ) return false;\n</code></pre>\n\n<hr>\n\n<h2>Editor points</h2>\n\n<p>Further, I completely switched to <a href=\"https://code.visualstudio.com/\" rel=\"nofollow noreferrer\">Visual Studio Code</a>, where it looks just great for a reader:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BjRz4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BjRz4.png\" alt=\"string_contains_integer() in Visual Studio Code\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T17:37:24.163",
"Id": "424804",
"Score": "1",
"body": "Personally, I don't like the whitespace after `(` and function names, or before `)`. But that's merely a preference, and it's good that you have a *consistent* style. Many of us would recommend putting the body statement of `if`, `for` etc. on a new line, and many of us recommend using braces even for a single statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T19:16:04.323",
"Id": "424811",
"Score": "0",
"body": "@TobySpeight Thank you for your kind insights. Let me try it and see what fits me best."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-05T08:08:21.860",
"Id": "219739",
"ParentId": "211470",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211472",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T11:36:18.883",
"Id": "211470",
"Score": "2",
"Tags": [
"c++",
"beginner",
"strings",
"integer"
],
"Title": "BigInteger check in C++ from a string"
} | 211470 |
<p>I am practicing move semantics and placement new by writing a custom Vector class but I am not confident that I use them right.
I would really appreciate some pieces of advice regarding my code.</p>
<p>Here is my Vector header</p>
<pre><code>#ifndef VECTOR_VECTOR_H
#define VECTOR_VECTOR_H
#include <iostream>
#include <utility>
#include <iterator>
#include <algorithm>
#define _NOEXCEPT noexcept
template < typename T > class Vector { public: explicit Vector( size_t = INITIAL_CAPACITY );
Vector( size_t, const T & );
template < typename InputIterator > Vector( InputIterator, InputIterator );
Vector( const Vector & );
Vector( Vector && ) _NOEXCEPT;
Vector &operator=( const Vector & );
Vector &operator=( Vector && ) _NOEXCEPT;
Vector &operator=( std::initializer_list < T > );
~Vector();
template < class InputIterator > void assign( InputIterator first, InputIterator last );
void assign( size_t n, const T &val );
void assign( std::initializer_list < T > il );
void push_back( const T & );
void push_back( T && );
void pop_back() _NOEXCEPT;
void reserve( size_t );
void resize( size_t );
void resize( size_t, const T & );
T &operator[]( size_t );
const T &operator[]( size_t ) const;
T &at( size_t );
const T &at( size_t ) const;
T &front();
const T &front() const;
T &back();
const T &back() const;
T *data() _NOEXCEPT;
const T *data() const _NOEXCEPT;
bool empty() const _NOEXCEPT;
size_t size() const _NOEXCEPT;
size_t capacity() const _NOEXCEPT;
bool contains( const T & ) const _NOEXCEPT;
void shrink_to_fit();
void swap( Vector & );
void clear() _NOEXCEPT;
#include "const_iterator.h"
#include "iterator.h"
#include "const_reverse_iterator.h"
#include "reverse_iterator.h"
iterator begin() _NOEXCEPT { return iterator( m_data ); }
iterator end() _NOEXCEPT { return iterator( m_data + m_size ); }
reverse_iterator rbegin() _NOEXCEPT { return reverse_iterator( m_data + m_size - 1 ); }
reverse_iterator rend() _NOEXCEPT { return reverse_iterator( m_data
- 1 ); }
const_iterator begin() const _NOEXCEPT { return const_iterator( m_data ); }
const_iterator end() const _NOEXCEPT { return const_iterator( m_data + m_size ); }
const_reverse_iterator rbegin() const _NOEXCEPT { return const_reverse_iterator( m_data + m_size - 1 ); }
const_reverse_iterator rend() const _NOEXCEPT { return const_reverse_iterator( m_data - 1 ); }
const_iterator cbegin() const _NOEXCEPT { return const_iterator( m_data ); }
const_iterator cend() const _NOEXCEPT { return const_iterator( m_data + m_size ); }
const_reverse_iterator crbegin() const _NOEXCEPT { return const_reverse_iterator( m_data + m_size - 1 ); }
const_reverse_iterator crend() const _NOEXCEPT { return const_reverse_iterator( m_data - 1 ); }
iterator erase( const_iterator );
iterator erase( const_iterator, const_iterator );
iterator insert( const_iterator position, const T &val );
iterator insert( const_iterator position, size_t n, const T &val );
template < class InputIterator > iterator insert( const_iterator position, InputIterator first, InputIterator last );
iterator insert( const_iterator position, T &&val );
iterator insert( const_iterator position, std::initializer_list < T > il );
private: void allocateMemory_( T *&, size_t );
void moveFrom_( Vector && ) _NOEXCEPT;
void destructObjects_() _NOEXCEPT;
bool makeSpace( iterator, size_t );
private: T *m_data; size_t m_size; size_t m_capacity;
static const int INITIAL_CAPACITY = 2; static const int FACTOR
= 2; };
template < typename T > bool operator==( const Vector < T > &lhs, const Vector < T > &rhs );
template < typename T > bool operator!=( const Vector < T > &lhs, const Vector < T > &rhs );
template < typename T > bool operator>( const Vector < T > &lhs, const Vector < T > &rhs );
template < typename T > bool operator>=( const Vector < T > &lhs, const Vector < T > &rhs );
template < typename T > bool operator<( const Vector < T > &lhs, const Vector < T > &rhs );
template < typename T > bool operator<=( const Vector < T > &lhs, const Vector < T > &rhs );
#include "vector_implementations.h"
#endif //VECTOR_VECTOR_H
</code></pre>
<p>My Vector implementations are in a separate header for readability purposes.</p>
<pre><code>#ifndef VECTOR_VECTOR_IMPLEMENTATIONS_H
#define VECTOR_VECTOR_IMPLEMENTATIONS_H
template < typename T >
inline Vector < T >::Vector( size_t capacity ) :m_data( nullptr ), m_size( 0 ), m_capacity( capacity ) {
allocateMemory_( m_data, m_capacity );
}
template < typename T >
inline Vector < T >::Vector( const Vector &rhs ) : Vector( rhs . m_size ) {
std::copy( rhs . begin(), rhs . end(), begin());
}
template < typename T >
inline Vector < T >::Vector( Vector &&rhs ) _NOEXCEPT {
moveFrom_( std::move( rhs ));
}
template < typename T >
inline Vector < T > &Vector < T >::operator=( const Vector &rhs ) {
if ( this != &rhs ) {
//copy-swap idiom
Vector tmp( rhs );
swap( tmp );
}
return *this;
}
template < typename T >
inline Vector < T > &Vector < T >::operator=( Vector &&rhs ) _NOEXCEPT {
if ( this != &rhs ) {
clear();
moveFrom_( std::move( rhs ));
}
return *this;
}
template < typename T >
inline Vector < T >::~Vector() {
clear();
}
template < typename T >
inline void Vector < T >::pop_back() _NOEXCEPT {
m_data[ --m_size ] . ~T();
}
template < typename T >
inline void Vector < T >::push_back( const T &element ) {
if ( !m_data || m_size == m_capacity ) {
reserve( m_capacity ? m_capacity * FACTOR : INITIAL_CAPACITY );
}
new( m_data + m_size )T( element );
++m_size;
}
template < typename T >
inline void Vector < T >::push_back( T &&element ) {
if ( !m_data || m_size == m_capacity ) {
reserve( m_capacity ? m_capacity * FACTOR : INITIAL_CAPACITY );
}
new( m_data + m_size )T( std::move( element ));
++m_size;
}
template < typename T >
inline T &Vector < T >::operator[]( size_t idx ) {
return *( m_data + idx );
}
template < typename T >
inline const T &Vector < T >::operator[]( size_t idx ) const {
return *( m_data + idx );
}
template < typename T >
inline T &Vector < T >::at( size_t idx ) {
if ( idx >= m_size ) {
throw ( std::out_of_range( "Invalid index" ));
}
return *( m_data + idx );
}
template < typename T >
inline const T &Vector < T >::at( size_t idx ) const {
if ( idx >= m_size ) {
throw ( std::out_of_range( "Invalid index" ));
}
return *( m_data + idx );
}
template < typename T >
inline T &Vector < T >::front() {
return *m_data;
}
template < typename T >
inline const T &Vector < T >::front() const {
return *m_data;
}
template < typename T >
inline T &Vector < T >::back() {
return *( m_data + m_size - 1 );
}
template < typename T >
inline const T &Vector < T >::back() const {
return *( m_data + m_size - 1 );
}
template < typename T >
inline T *Vector < T >::data() _NOEXCEPT {
return m_data;
}
template < typename T >
inline const T *Vector < T >::data() const _NOEXCEPT {
return m_data;
}
template < typename T >
inline bool Vector < T >::empty() const _NOEXCEPT {
return ( m_size == 0 );
}
template < typename T >
inline size_t Vector < T >::size() const _NOEXCEPT {
return m_size;
}
template < typename T >
inline size_t Vector < T >::capacity() const _NOEXCEPT {
return m_capacity;
}
template < typename T >
inline bool Vector < T >::contains( const T &element ) const _NOEXCEPT {
for ( int i = 0 ;
i < m_size ;
++i ) {
if ( m_data[ i ] == element ) {
return true;
}
}
return false;
}
template < typename T >
inline void Vector < T >::shrink_to_fit() {
Vector( *this ) . swap( *this );
}
template < typename T >
inline void Vector < T >::swap( Vector &rhs ) {
//check ADL look up
using std::swap;
swap( m_data, rhs . m_data );
swap( m_size, rhs . m_size );
swap( m_capacity, rhs . m_capacity );
}
template < typename T >
inline void Vector < T >::clear() _NOEXCEPT {
destructObjects_();
operator delete( m_data );
m_capacity = 0;
}
template < typename T >
inline void Vector < T >::allocateMemory_( T *&destination, size_t capacity ) {
destination = static_cast< T * >( operator new[]( capacity * sizeof( T )));
}
template < typename T >
inline void Vector < T >::moveFrom_( Vector &&rhs ) _NOEXCEPT {
m_data = rhs . m_data;
rhs . m_data = nullptr;
m_size = rhs . m_size;
m_capacity = rhs . m_capacity;
}
template < typename T >
inline void Vector < T >::destructObjects_() _NOEXCEPT {
while ( !empty()) {
pop_back();
}
}
template < typename T >
inline void Vector < T >::reserve( size_t size ) {
if ( size <= m_capacity ) {
return;
}
T *newData = nullptr;
allocateMemory_( newData, size );
size_t i = 0;
for ( ; i < m_size ;
++i ) {
new( newData + i )T( std::move( m_data[ i ] ));
}
clear();
m_size = i;
m_data = newData;
m_capacity = size;
}
template < typename T >
inline void Vector < T >::resize( size_t size ) {
resize( size, T());
}
template < typename T >
inline void Vector < T >::resize( size_t size, const T &value ) {
reserve( size );
if ( size <= m_size ) {
while ( m_size > size ) {
pop_back();
}
} else {
while ( m_size < size ) {
push_back( value );
}
}
}
template < typename T >
inline typename Vector < T >::iterator Vector < T >::erase( typename Vector < T >::const_iterator position ) {
//std::advance(it,std::distance(cbegin(),position));
//iterator iter = begin() + ( position - cbegin() );
//std::move( iter + 1, end(), iter );
//pop_back();
//return iter;
return erase( position, position + 1 );
}
template < typename T >
inline typename Vector < T >::iterator Vector < T >::erase
( typename Vector < T >::const_iterator first, typename Vector < T >::const_iterator last ) {
//UB on invalid range
iterator iter = begin() + ( first - cbegin());
int removed_elements = last - first;
std::move( last, cend(), iter );
while ( removed_elements-- ) {
pop_back();
}
return iter;
}
template < typename T >
bool Vector < T >::makeSpace( Vector::iterator position, size_t space ) {
size_t elementsToMove = end() - position;
std::cout << "POSITION " << elementsToMove << std::endl;
if ( m_size + space >= m_capacity ) {
reserve( m_capacity ? m_capacity * FACTOR : INITIAL_CAPACITY );
}
for ( int i = 0 ;
i < elementsToMove ;
++i ) {
new( m_data + m_size + space - i ) T( std::move( m_data[ m_size - i ] ));
}
m_size += space;
}
template < typename T >
Vector < T >::Vector( size_t n, const T &val ) :Vector( n ) {
while ( n-- ) {
push_back( val );
}
}
template < typename T >
template < typename InputIterator >
Vector < T >::Vector( InputIterator first, InputIterator last ) {
size_t numElements = last - first;
allocateMemory_( m_data, numElements );
while ( first != last ) {
push_back( *first );
++first;
}
}
template < typename T >
Vector < T > &Vector < T >::operator=( std::initializer_list < T > il ) {
Vector tmp( il . begin(), il . end());
swap( tmp );
return *this;
}
template < typename T >
Vector::iterator Vector < T >::insert( Vector::const_iterator position, const T &val ) {
size_t offset = position - cbegin();
makeSpace( begin() + offset - 1, 1 );
m_data[ offset ] = val;
return ( begin() + offset );
}
template < typename T >
Vector::iterator Vector < T >::insert( Vector::const_iterator position, size_t n, const T &val ) {
size_t offset = position - cbegin();
makeSpace( begin() + offset - 1, n );
for ( int i = 0 ; i < n ; ++i ) {
m_data[ offset + i ] = val;
}
return ( begin() + offset );
}
template < typename T >
template < class InputIterator >
Vector::iterator Vector < T >::insert( Vector::const_iterator position, InputIterator first, InputIterator last ) {
size_t offset = position - cbegin();
makeSpace( begin() + offset - 1, last - first );
int i = 0;
while ( first != last ) {
m_data[ offset + i ] = *first;
++first;
++i;
}
return ( begin() + offset );
}
template < typename T >
Vector::iterator Vector < T >::insert( Vector::const_iterator position, T &&val ) {
size_t offset = position - cbegin();
makeSpace( begin() + offset - 1, 1 );
m_data[ offset ] = std::move( val );
return ( begin() + offset );
}
template < typename T >
Vector::iterator Vector < T >::insert( Vector::const_iterator position, std::initializer_list < T > il ) {
return insert( position, il . begin(), il . end());
}
template < typename T >
template < class InputIterator >
void Vector < T >::assign( InputIterator first, InputIterator last ) {
swap( Vector( first, last ));
}
template < typename T >
void Vector < T >::assign( size_t n, const T &val ) {
swap( Vector( n, val ));
}
template < typename T >
void Vector < T >::assign( std::initializer_list < T > il ) {
swap( Vector( il ));
}
template < typename T >
inline bool operator==( const Vector < T > &lhs, const Vector < T > &rhs ) {
if ( lhs . size() != rhs . size()) {
return false;
}
for ( int i = 0 ;
i < lhs . size() ;
++i ) {
if ( lhs[ i ] != rhs[ i ] ) {
return false;
}
}
return true;
}
template < typename T >
inline bool operator!=( const Vector < T > &lhs, const Vector < T > &rhs ) {
return !( lhs == rhs );
}
template < typename T >
inline bool operator>( const Vector < T > &lhs, const Vector < T > &rhs ) {
return rhs < lhs;
}
template < typename T >
inline bool operator>=( const Vector < T > &lhs, const Vector < T > &rhs ) {
return !( lhs < rhs );
}
template < typename T >
inline bool operator<( const Vector < T > &lhs, const Vector < T > &rhs ) {
int i = 0;
while ( i < lhs . size() && i < rhs . size() && lhs[ i ] == rhs[ i ] ) {
++i;
}
if ( i == lhs . size() || i == rhs . size()) {
return lhs . size() < rhs . size();
}
return lhs[ i ] < rhs[ i ];
}
template < typename T >
inline bool operator<=( const Vector < T > &lhs, const Vector < T > &rhs ) {
return !( rhs < lhs );
}
#endif //VECTOR_VECTOR_IMPLEMENTATIONS_H
</code></pre>
<p>And I will just post the code for one of the iterators type, because the rest are identical.</p>
<pre><code>#ifndef VECTOR_CONST_REVERSE_ITERATOR_H
#define VECTOR_CONST_REVERSE_ITERATOR_H
class const_reverse_iterator : public std::iterator<std::random_access_iterator_tag, const T>
{
friend class Vector;
friend class const_iterator;
public:
const_reverse_iterator( const T* data = nullptr ) : m_data( data )
{}
const T& operator*() const
{
return *m_data;
}
const T* operator->() const
{
return m_data;
}
const_reverse_iterator& operator++()
{
--m_data;
return *this;
}
const_reverse_iterator operator++( int )
{
const_reverse_iterator res( *this );
--( *this );
return res;
}
const_reverse_iterator& operator+=( int n )
{
while ( --n )
++( *this );
return *this;
}
const_reverse_iterator operator+( int n ) const
{
const_reverse_iterator tmp( *this );
tmp -= n;
return tmp;
}
const_reverse_iterator& operator--()
{
++m_data;
return *this;
}
const_reverse_iterator operator--( int )
{
const_reverse_iterator res( *this );
++( *this );
return res;
}
const_reverse_iterator& operator-=( int n )
{
while ( n-- )
--( *this );
return *this;
}
const_reverse_iterator operator-( int n ) const
{
const_reverse_iterator tmp( *this );
tmp += n;
return tmp;
}
ptrdiff_t operator- ( const const_reverse_iterator& rhs ) const
{
return m_data - rhs.m_data;
}
const_iterator base()
{
return const_iterator( m_data + 1 );
}
const T& operator[] ( size_t ind ) const
{
return ( *( m_data - ind ) );
}
bool operator==( const const_reverse_iterator& other ) const _NOEXCEPT
{
return m_data == other.m_data;
}
bool operator!=( const const_reverse_iterator& other ) const _NOEXCEPT
{
return !( other == *this );
}
bool operator<( const const_reverse_iterator& other ) const _NOEXCEPT
{
return m_data > other.m_data;
}
bool operator>( const const_reverse_iterator& other ) const _NOEXCEPT
{
return *this < other;
}
private:
const T* m_data;
};
#endif //VECTOR_CONST_REVERSE_ITERATOR_H
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T17:17:56.683",
"Id": "408945",
"Score": "0",
"body": "Ooooh. This is a big NoNo. `_NOEXCEPT` Leading underscore followed by a capitol letter. Don't do that. In fact why have it at all. We know your code needs to be at least C++11 as it has move semantics built in and C++11 has the keyword `noexcept`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:50:31.377",
"Id": "408959",
"Score": "0",
"body": "Please don't edit your code to incorporate advice from answers. I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:56:27.670",
"Id": "408961",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ: If you look at those changes, they were pure whitespace/formatting that looked like unintentional copy/paste problems or something. Martin York's answer addresses this mess, but I'm not sure it was even intentional in the first place. I mean it seems so obviously bad style that I hope nobody did that on purpose, but it is possible. Maybe the OP can clarify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:58:32.470",
"Id": "408963",
"Score": "1",
"body": "@peterCordes I thought that at first as well, but then on further inspection I noticed that the member variables had been split, per Martin's advice: \"_My gosh. `private: T *m_data; size_t m_size; size_t m_capacity;` One variable per line please._\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T19:08:28.290",
"Id": "408967",
"Score": "0",
"body": "My original code isn't with 1000 things per line. It got reformatted when I copied pasted it here and I didn't notice it until it was mentioned. I was going to fix just that for readability reason. I leave an empty line between functions declarations just to be more clear, i am not going to have some lines looking like that on purpose. .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T19:08:33.627",
"Id": "408968",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ: They [commented on Martin's answer](https://codereview.stackexchange.com/questions/211477/c11-vector-with-move-semantics?noredirect=1#comment408956_211493) that it was a copy/paste glitch. Still unfortunate to waste people's time reviewing an unintentionally badly formatted question, but that damage is already done and the long-term usefulness of this question is probably improved if we let the formatting accidents be fixed."
}
] | [
{
"body": "<ol>\n<li>We have consistently misspelt <code>std::size_t</code>.</li>\n<li><code>_NOEXCEPT</code> is a <a href=\"http://eel.is/c++draft/lex.name#3\" rel=\"noreferrer\">reserved identifier</a> and may even be expanded as a macro.</li>\n<li>We should have an initializer-list constructor - as a guide, construction and assignment argument lists should parallel each other.</li>\n<li><code>inline</code> is redundant and just adds clutter.</li>\n<li><code>makeSpace()</code> has no return statement.</li>\n<li>Logging output should go to <code>std::clog</code>, not <code>std::cout</code>.</li>\n<li>Outside of the class definition, the return type of <code>insert()</code> and other functions must be written as <code>typename Vector<T>::iterator</code> rather than <code>Vector::iterator</code> (or use trailing return type syntax).</li>\n<li>Don't assume that an input iterator has <code>operator-()</code> (but do provide optimised overloads where <code>std::distance()</code> is usable).</li>\n<li>We can't use <code>T::operator=</code> to populate uninitialized memory with an object - we need to construct in-place, or use one of the <code>std::uninitialized_copy()</code> family of functions.</li>\n<li>We don't need <code>moveFrom_()</code> if we implement move construction and assignment using <code>swap()</code>.</li>\n<li>We can simplify copy-assign by implementing it in terms of move-assign (see below).</li>\n<li>Relational operators could be simpler, if we used <code>std::lexicographical_compare()</code> instead of writing those loops.</li>\n<li>The <code>contains()</code> member function is equivalent to calling <code>std::find()</code> and comparing the result against an end iterator.</li>\n<li>There's too much whitespace for my taste - I'd certainly remove that around the <code>.</code> operator, and I suggest grouping related declarations on adjacent lines. Spaces around <code><</code> and <code>></code> makes template arguments harder to distinguish from the <code><</code> and <code>></code> operators.</li>\n<li>Inheriting from <code>std::iterator</code> is now deprecated.</li>\n<li>We could use <code>std::reverse_iterator</code> to create a reverse iterator from a forward iterator.</li>\n<li>We could use a plain pointer as forward iterator.</li>\n</ol>\n\n<hr>\n\n<p>Regarding the iterators, I successfully replaced those four files with:</p>\n\n<pre><code>using iterator = T*;\nusing const_iterator = const T*;\nusing reverse_iterator = std::reverse_iterator<iterator>;\nusing const_reverse_iterator = std::reverse_iterator<const_iterator>;\n</code></pre>\n\n<p>We need to also remove the <code>-1</code> from the reverse begin/end (and we can further simplify):</p>\n\n<pre><code>iterator begin() noexcept { return m_data; }\niterator end() noexcept { return m_data + m_size; }\n\nconst_iterator begin() const noexcept { return m_data; }\nconst_iterator end() const noexcept { return m_data + m_size; }\n\nreverse_iterator rbegin() noexcept { return reverse_iterator(end()); }\nreverse_iterator rend() noexcept { return reverse_iterator(begin()); }\n\nconst_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }\nconst_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }\n\nconst_iterator cbegin() const noexcept { return begin(); }\nconst_iterator cend() const noexcept { return end(); }\n\nconst_reverse_iterator crbegin() const noexcept { return rbegin(); }\nconst_reverse_iterator crend() const noexcept { return rend(); }\n</code></pre>\n\n<hr>\n\n<p>Copy-assign implemented in terms of move-assign:</p>\n\n<pre><code>template<typename T>\ninline Vector<T> &Vector<T>::operator=(const Vector& rhs)\n{\n return *this = Vector<T>{rhs};\n}\n</code></pre>\n\n<p>We can't implement copy-construct the same way, because passing by value depends on copy-construction, giving us a chicken-and-egg issue!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T17:53:40.620",
"Id": "408949",
"Score": "0",
"body": "@TobySpeight This surpassed my expectations. Learnt so much! Can't say Thank you enough"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:59:49.127",
"Id": "408964",
"Score": "3",
"body": "The copy-assign version is certainly neat syntax-wise... however it's not as efficient as it could be. If `*this` happens to have enough capacity for `rhs.size()` elements, then no allocation should be necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T19:06:12.940",
"Id": "408966",
"Score": "0",
"body": "Good point @Matthieu"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T21:06:42.957",
"Id": "408977",
"Score": "0",
"body": "@MatthieuM. Well, one should then also look at whether copy-constructing an element can throw."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:57:33.800",
"Id": "409010",
"Score": "0",
"body": "@Deduplicator: That's less of an issue; so long as your `push_back` implementation is exception-safe, then you can implement copy-construction with a `push_back` loop. You won't get the strong exception guarantee, but you'll get the basic one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:05:44.313",
"Id": "409011",
"Score": "0",
"body": "@Deduplicator: Though of course, I'd recommend using `this->assign` instead, and handle all this in `assign` where it needs be handled anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T09:08:34.367",
"Id": "409018",
"Score": "0",
"body": "@MatthieuM. push_back always checks if it needs to reallocate. If i do it in a loop with push_back, wouldnt that slow it down a bit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T09:16:43.423",
"Id": "409019",
"Score": "1",
"body": "@Michaela: Yes. So will using a naive for-loop instead of a vectorized copy when `T` is trivially copyable. There's always room for improvement :) Once you get the broad strokes right, though, unless you have very specific performance requirements... *Don't sweat the small stuff*. First make sure to get it right, then eliminate \"gross\" performance issues: (1) algorithmic, (2) memory, and only then start looking into micro-optimizations if it's still needed."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T15:01:56.807",
"Id": "211483",
"ParentId": "211477",
"Score": "8"
}
},
{
"body": "<h2>Overall</h2>\n<p>You need to use namespaces in your code. Nearly everybody and their granddaughter builds a <code>Vector</code> class at some point. So the likelhood of a clash is very high. Build yours into your own namespace (then you get not clashes).</p>\n<h2>Code Review</h2>\n<p>This is a good start.</p>\n<pre><code>#ifndef VECTOR_VECTOR_H\n#define VECTOR_VECTOR_H\n</code></pre>\n<p>But does not look very unique to me (especially since everybody builds a <code>Vector</code>). Add the namespace into this guard and you will have something at least reasonably unique.</p>\n<p>Don' do this.</p>\n<pre><code>#define _NOEXCEPT noexcept\n</code></pre>\n<p>In addition to <code>_NOEXCEPT</code> being a reserved identifier; why are you trying to obfuscate your code? Just put <code>noexcept</code> out there. Everybody understands it nowadays.</p>\n<p>That's a lot to put on one line!</p>\n<pre><code>template < typename T > class Vector { public: explicit Vector( size_t = INITIAL_CAPACITY );\n</code></pre>\n<p>In the rest of your code you put an empty line between every function (which I also find annoying) but here you force <strong>FOUR</strong> different things on a single line. Give the reader a break this needs to be broken up. Also group your methods into logical groups.</p>\n<p>OK. This is a good constructor. But do you actually need to specify a default value? Can that not be inferred by the value taking on the default constructed version of the type?</p>\n<pre><code> Vector( size_t, const T & );\n // I would have done\n Vector(size_t size, T const& init = T{});\n</code></pre>\n<p>I wish you would break the template stuff onto one row and the method stuff onto another row. That's a more common way of writing these declarations.</p>\n<pre><code> template < typename InputIterator > Vector( InputIterator, InputIterator );\n</code></pre>\n<p>OK. I see assignment to an initializer list but given this why can't I construct the vector with an initializer list? <strike>While we are at it why do you pass initializer lists by value?</strike>See comments below.</p>\n<pre><code> Vector &operator=( std::initializer_list < T > );\n\n void assign( std::initializer_list < T > il );\n</code></pre>\n<p>Nice Standard set of push operations.</p>\n<pre><code> void push_back( const T & );\n void push_back( T && );\n void pop_back() _NOEXCEPT;\n</code></pre>\n<p>But why don't I see an <code>emplace_back()</code> in the same area? Am I going to find it below?</p>\n<p>Including other header files inside a class (and thus probably a namespace). That's not a disaster waiting to happen (sarcasm). These header files are dependent on this header file. What happens if a user includes them directly. You should at least set up some header guards that makes it hard to do that accidentally.</p>\n<pre><code>#include "const_iterator.h"\n#include "iterator.h"\n#include "const_reverse_iterator.h"\n#include "reverse_iterator.h"\n</code></pre>\n<p>Don't really think you need any special iterator classes for a vector. A pointer to the member should work just fine (assuming contiguous memory for the data).</p>\n<pre><code> iterator begin() _NOEXCEPT { return iterator( m_data ); }\n iterator end() _NOEXCEPT { return iterator( m_data + m_size ); }\n</code></pre>\n<p>My gosh.</p>\n<pre><code>private: T *m_data; size_t m_size; size_t m_capacity;\n</code></pre>\n<p>One variable per line please. Also brave of you to use <code>T*</code> as the pointer type. Let's see if you get the allocation correct.</p>\n<p>Not sure why these are standalone methods. Why are they not members of the class?</p>\n<pre><code>template < typename T > bool operator==( const Vector < T > &lhs, const Vector < T > &rhs ); \ntemplate < typename T > bool operator!=( const Vector < T > &lhs, const Vector < T > &rhs ); \ntemplate < typename T > bool operator>( const Vector < T > &lhs, const Vector < T > &rhs ); \ntemplate < typename T > bool operator>=( const Vector < T > &lhs, const Vector < T > &rhs ); \ntemplate < typename T > bool operator<( const Vector < T > &lhs, const Vector < T > &rhs ); \ntemplate < typename T > bool operator<=( const Vector < T > &lhs, const Vector < T > &rhs );\n</code></pre>\n<p>OK. Copy swap idiom usually does not check for self-assignment.</p>\n<pre><code>template < typename T >\ninline Vector < T > &Vector < T >::operator=( const Vector &rhs ) {\n if ( this != &rhs ) {\n //copy-swap idiom\n Vector tmp( rhs );\n swap( tmp );\n }\n return *this;\n}\n</code></pre>\n<p>Yes. A self-assignment check will save you a lot if you actually do a self-assignment. But self-assignment is so vanishingly rare that you are actually pessimizing the normal action. Now this pessimization is a small cost but done so very frequently that the overall cost is on average higher than the cost of a self-assignment copy.</p>\n<pre><code>Prob(SelfAssigment) * {Cost Of SelfAssigment} < Prob(NormAssigment) * {Cost Of NormAssigment}\n</code></pre>\n<p>The standard way of writing this is:</p>\n<pre><code>// Pre Move semantics.\ntemplate < typename T >\ninline Vector < T > &Vector < T >::operator=(Vector rhs) {\n swap( rhs );\n return *this;\n}\n\n// Post Move semantics as passing by value and RValue ref causes\n// conflicting definitions for the compiler.\ntemplate < typename T >\ninline Vector < T > &Vector < T >::operator=(Vector const& rhs) {\n Vector tmp(rhs);\n swap( tmp );\n return *this;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:36:37.787",
"Id": "408956",
"Score": "2",
"body": "1. I havent actually written my code like that with 1000 stuff on one line. It just got reformatted when I copied-pasted. I will fix it now.\n2.I have heard it's a good practice to overload some operators as non-member functions. E.g [https://stackoverflow.com/questions/29999932/operator-overload-member-vs-non-member-when-only-same-type-objects-can-be-invo]\n3. I think emplace_back should use variadic template arguments, something I havent read anything about yet, which is why it is not there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:44:57.267",
"Id": "408957",
"Score": "1",
"body": "Non-member comparison operators do make sense, according to the common guideline (they can be implemented using the public interface, so don't make them members)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T21:28:43.283",
"Id": "408979",
"Score": "1",
"body": "`std::initializer_list` is a reference type, and *always* passed by value, unless perfect forwarding interferes. The comparison-operators are probably not members because there is no need for them to be. Also, it allows for more flexibility when allocator-support is added later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T14:30:22.743",
"Id": "409040",
"Score": "0",
"body": "Copy-assignment with move-semantics: `return *this = Vector(rhs);`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T18:16:03.653",
"Id": "211493",
"ParentId": "211477",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "211483",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T14:28:12.503",
"Id": "211477",
"Score": "8",
"Tags": [
"c++",
"c++11",
"vectors"
],
"Title": "C++11 Vector with move semantics"
} | 211477 |
<p>I'm writing a small <a href="https://en.wikipedia.org/wiki/Financial_Information_eXchange" rel="nofollow noreferrer">FIX</a> client in Python (2.7, constraint I cannot waive for now, unfortunately).</p>
<p>There will be multiple sockets, connecting to different ports, so I thought I'd create a <code>SocketManager</code> to keep a list of sockets and have <code>select.epoll</code> <code>register()</code> them all.</p>
<p>Each socket is wrapped by a <code>ThinSocketWrapper</code> class, which basically adds a lock, two string buffers (to receive and send) and a Queue (to receive messages):</p>
<pre><code>class ThinSocketWrapper(socket):
def __init__(self, *args, **kwargs):
self.BUFLEN = 4096
self.lock = RLock()
self.recvBuffer = ''
self.sendBuffer = ''
self.recvQueue = kwargs.pop('recvQueue')
super(ThinSocketWrapper, self).__init__(*args, **kwargs)
</code></pre>
<p>Questions:</p>
<ol>
<li><p>The queue is created by the caller and passed in as an argument. This seems a bit messy to me. Would it be better to create the queue from within this class and make it accessible (e.g. through a <code>getRecvQueue</code> method)?</p></li>
<li><p>The same way I could create a <code>sendQueue</code> in <code>ThinSocketWrapper</code> and make it accessible through <code>getSendQueue()</code>. The purpose of this queue is that it will be swept by a background thread looking for messages to send. Where should this thread live? Within the <code>ThinSocketWrapper</code> class? Are there better ways of sweeping a queue? Like a <code>select.epoll</code> for queues?</p>
<p>The <code>SocketManager</code> is basically a thread, whose main loop looks like this:</p>
<pre><code>class SocketManager(Thread):
def run(self):
while True:
try:
events = self.epoll.poll(TIMEOUT)
except IOError as e:
if e.errno == errno.EINTR:
continue
for socket, event in events:
try:
if event & (select.EPOLLIN | select.EPOLLPRI):
self.readEvent(socket)
elif event & select.EPOLLOUT:
self.writeEvent(socket)
elif event & (select.EPOLLHUP | select.EPOLLERR):
self.unregister(socket)
except:
socket.close()
self.unregister(socket)
</code></pre>
<p><code>readEvent</code> is defined as follows:</p>
<pre><code> def readEvent(self, socket):
try:
while True:
data = socket.recv(socket.BUFLEN)
if not data:
raise RuntimeError('Socket closed (read)')
socket.recvBuffer += data
except socket.error as e:
if e.errno != errno.EAGAIN:
raise
socket.recvQueue.append(socket.recvBuffer)
socket.recvBuffer = ''
</code></pre></li>
<li><p>At the end, when we're done receiving, we basically convert whatever we received in pseudo-messages, that is we copy everything in <code>recvBuffer</code> to <code>recvQueue</code>. I say "pseudo" because it might well be that the endpoint sends us multiple messages back to back, which would be impossible to split unless we look at the content: in that situation, we would end up with multiple messages in the same item of the queue.</p>
<p>This tells me that packing what has been received into messages is not this class' responsibility (in fact it should be a layer higher, from the point of view of the networking stack). What would be a nicer alternative?</p></li>
</ol>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T16:23:38.697",
"Id": "211487",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"socket"
],
"Title": "Managing multiple sockets in a network client in Python"
} | 211487 |
<p>I have coded up the layout using the following Dribbble shot:</p>
<p><a href="https://dribbble.com/shots/5382121-Nike-Future" rel="nofollow noreferrer">https://dribbble.com/shots/5382121-Nike-Future</a></p>
<p>To help get better at layouts. </p>
<p>This is using a mix of Grid and Flexbox, but an area where I think I may need to revisit is the play button which is using the old method of <code>position: absolute</code> to veritally align it to the middle.</p>
<p>The ideal solution would be to have the play button positioned on the middle grid line. If people have optimisations I would be happy to hear them.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
--main-orange: #ff4644;
--main-blue: #2f333e;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: sans-serif;
}
.wrapper {
display: grid;
height: 100vh;
min-height: 800px;
grid-template-columns: 50fr 40fr 10fr;
grid-template-rows: 50fr 50fr;
position: relative;
}
.main-area {
background-color: #fff;
grid-column: 1 / 2;
grid-row: 1 / 3;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.play-btn {
width: 75px;
height: 75px;
background-color: var(--main-orange);
border-radius: 40px;
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
color: var(--main-blue);
text-decoration: none;
transition: 0.3s;
}
.play-btn:hover {
box-shadow: 0px 30px 30px 0px rgba(255, 100, 68, 0.4);
color: #fff;
}
.main-nav {
width: 100%;
display: flex;
justify-content: flex-end;
padding: 60px 75px;
}
.main-nav a {
color: var(--main-blue);
text-decoration: none;
text-transform: uppercase;
}
.logo-area {
margin-right: auto;
}
.logo-area img {
width: 75px;
}
.menu-item {
padding-left: 15px;
padding-right: 15px;
letter-spacing: 7.5px;
font-size: 0.75rem;
transition: 0.3s;
}
.menu-item:hover {
color: var(--main-orange);
}
.menu-item:last-child {
padding-right: 0;
}
.nike-box {
width: 180px;
word-break: break-all;
margin-left: 75px;
justify-self: flex-end;
}
.nike-box h2 {
font-family: 'Roboto Mono', monospace;
text-transform: uppercase;
letter-spacing: 3rem;
font-size: 4rem;
font-weight: 300;
}
.img-area {
grid-column-start: 2;
grid-column-end: 3;
grid-row-start: 1;
grid-row-end: 3;
background-image: url('https://images.pexels.com/photos/733505/pexels-photo-733505.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
background-size: cover;
background-position: top center;
background-repeat: no-repeat;
}
.search-area {
grid-column: 3 / 4;
grid-row: 1 / 2;
background-color: var(--main-blue);
}
.social-area {
grid-column: 3 / 4;
grid-row: 2 / 3;
background-color: var(--main-orange);
color: #fff;
display: flex;
}
.search-icon-container {
display: flex;
flex-direction: column;
width: 100%;
align-items: center;
padding-top: 60px;
color: #fff;
}
.social-links {
padding: 0;
list-style-type: none;
display: flex;
flex-direction: column;
align-self: flex-end;
width: 100%;
align-items: center;
padding-bottom: 60px
}
.social-links li {
transform: rotate(-90deg);
margin-bottom: 30px;
font-size: 0.75rem;
}
.social-links li:last-child {
margin-bottom: 0;
}
.social-links li a {
color: #fff;
text-decoration: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:100,300,400" rel="stylesheet">
<script defer src="https://use.fontawesome.com/releases/v5.6.3/js/all.js" integrity="sha384-EIHISlAOj4zgYieurP0SdoiBYfGJKkgWedPHH4jCzpCXLmzVsw1ouK59MuUtP4a1" crossorigin="anonymous"></script>
</head>
<div class="wrapper">
<a href="#" class="play-btn">&#9654;</a>
<section class="main-area">
<nav class="main-nav">
<a href="#" class="logo-area"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Logo_NIKE.svg/400px-Logo_NIKE.svg.png" alt=""></a>
<a href="#" class="menu-item">Mens</a><a href="#" class="menu-item">Womens</a>
</nav>
<div class="nike-box">
<h2>Nike</h2>
</div>
</section>
<section class="img-area"></section>
<section class="search-area">
<div class="search-icon-container">
<i class="fas fa-search"></i>
</div>
</section>
<section class="social-area">
<ul class="social-links">
<li><a href="#">Fb</a></li>
<li><a href="#">In</a></li>
<li><a href="#">Tw</a></li>
</ul>
</section>
</div></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>I would move the play button inside the image section.\nIt make more sense to have a container, not empty, used to host it also by a semantic point of view.\nBy setting it up to <code>display: flex;</code> it will be pretty easy to position it.\nOf course, you'll need to adapt the design to smaller devices.</p>\n\n<p>See code snippet for details.</p>\n\n<p>Finally, even if it \"sounds\" correct, I'd use <code>div</code> in place of <code>section</code> for non semantic (I.E. no header, no footer, no content) portions of your page.</p>\n\n<p>I hope this helps.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>:root {\n --main-orange: #ff4644;\n --main-blue: #2f333e;\n}\n\n* {\n box-sizing: border-box;\n}\n\nbody {\n margin: 0;\n font-family: sans-serif;\n}\n\n.wrapper {\n display: grid;\n height: 100vh;\n min-height: 800px;\n grid-template-columns: 50fr 40fr 10fr;\n grid-template-rows: 50fr 50fr;\n position: relative;\n}\n\n.main-area {\n background-color: #fff;\n grid-column: 1 / 2;\n grid-row: 1 / 3;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n\n.play-btn {\n width: 75px;\n height: 75px;\n background-color: var(--main-orange);\n border-radius: 40px;\n position: relative;\n left: -37px;\n display: flex;\n flex-direction: column;\n justify-content: center;\n text-align: center;\n color: var(--main-blue);\n text-decoration: none;\n transition: 0.3s;\n}\n\n.play-btn:hover {\n box-shadow: 0px 30px 30px 0px rgba(255, 100, 68, 0.4);\n color: #fff;\n}\n\n.main-nav {\n width: 100%;\n display: flex;\n justify-content: flex-end;\n padding: 60px 75px;\n}\n\n.main-nav a {\n color: var(--main-blue);\n text-decoration: none;\n text-transform: uppercase;\n}\n\n.logo-area {\n margin-right: auto;\n}\n\n.logo-area img {\n width: 75px;\n}\n\n.menu-item {\n padding-left: 15px;\n padding-right: 15px;\n letter-spacing: 7.5px;\n font-size: 0.75rem;\n transition: 0.3s;\n}\n\n.menu-item:hover {\n color: var(--main-orange);\n}\n\n.menu-item:last-child {\n padding-right: 0;\n}\n\n.nike-box {\n width: 180px;\n word-break: break-all;\n margin-left: 75px;\n justify-self: flex-end;\n}\n\n.nike-box h2 {\n font-family: 'Roboto Mono', monospace;\n text-transform: uppercase;\n letter-spacing: 3rem;\n font-size: 4rem;\n font-weight: 300;\n}\n\n.img-area {\n grid-column-start: 2;\n grid-column-end: 3;\n grid-row-start: 1;\n grid-row-end: 3;\n background-image: url('https://images.pexels.com/photos/733505/pexels-photo-733505.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');\n background-size: cover;\n background-position: top center;\n background-repeat: no-repeat;\n display: flex;\n align-items: center;\n}\n\n.search-area {\n grid-column: 3 / 4;\n grid-row: 1 / 2;\n background-color: var(--main-blue);\n}\n\n.social-area {\n grid-column: 3 / 4;\n grid-row: 2 / 3;\n background-color: var(--main-orange);\n color: #fff;\n display: flex;\n}\n\n.search-icon-container {\n display: flex;\n flex-direction: column;\n width: 100%;\n align-items: center;\n padding-top: 60px;\n color: #fff;\n}\n\n.social-links {\n padding: 0;\n list-style-type: none;\n display: flex;\n flex-direction: column;\n align-self: flex-end;\n width: 100%;\n align-items: center;\n padding-bottom: 60px\n}\n\n.social-links li {\n transform: rotate(-90deg);\n margin-bottom: 30px;\n font-size: 0.75rem;\n}\n\n.social-links li:last-child {\n margin-bottom: 0;\n}\n\n.social-links li a {\n color: #fff;\n text-decoration: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><head>\n <link href=\"https://fonts.googleapis.com/css?family=Roboto+Mono:100,300,400\" rel=\"stylesheet\">\n <script defer src=\"https://use.fontawesome.com/releases/v5.6.3/js/all.js\" integrity=\"sha384-EIHISlAOj4zgYieurP0SdoiBYfGJKkgWedPHH4jCzpCXLmzVsw1ouK59MuUtP4a1\" crossorigin=\"anonymous\"></script>\n</head>\n<div class=\"wrapper\">\n\n <section class=\"main-area\">\n <nav class=\"main-nav\">\n <a href=\"#\" class=\"logo-area\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Logo_NIKE.svg/400px-Logo_NIKE.svg.png\" alt=\"\"></a>\n <a href=\"#\" class=\"menu-item\">Mens</a><a href=\"#\" class=\"menu-item\">Womens</a>\n </nav>\n\n <div class=\"nike-box\">\n <h2>Nike</h2>\n </div>\n\n </section>\n\n <section class=\"img-area\">\n <a href=\"#\" class=\"play-btn\">&#9654;</a>\n </section>\n\n <section class=\"search-area\">\n <div class=\"search-icon-container\">\n <i class=\"fas fa-search\"></i>\n </div>\n </section>\n\n <section class=\"social-area\">\n <ul class=\"social-links\">\n <li><a href=\"#\">Fb</a></li>\n <li><a href=\"#\">In</a></li>\n <li><a href=\"#\">Tw</a></li>\n </ul>\n </section>\n\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-29T08:57:56.847",
"Id": "212450",
"ParentId": "211489",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T16:34:57.790",
"Id": "211489",
"Score": "3",
"Tags": [
"css"
],
"Title": "CSS Grid and Flexbox use"
} | 211489 |
<p>I'm building a Summary page for merchant activity in a marketplace with react and redux.</p>
<p>The application has already a structure where there is a "MerchantContianer"</p>
<pre><code>class MerchantContainer extends Component {
render() {
const merchList = [];
for(let key in this.props.merchants) {
for(let id in this.props.merchants[key].byId) {
let row = this.props.merchants[key].byId[id];
merchList.push((
<Merchant
type={key}
key={id}
date={row.date}
name={row.name}
amount={row.amount}
delete={() => this.props.onDeleteRow(row.id, key)} />
));
}
};
return (
<div className={classes.List}>
{merchList}
</div>
)
}
}
const mapStateToProps = state => {
return {
merchants: state.list.merchants
};
};
const mapDispatchtoProps = dispatch => {
return {
onDeleteRow: (id, type) => {dispatch(actions.deleteMerchantsFromList(id, type))}
};
};
export default connect(mapStateToProps, mapDispatchtoProps)(MerchantContainer);
</code></pre>
<p>and a Merchant component</p>
<pre><code>const Merchant = props => {
const classArr = [classes.Merchant, classes[props.type]].join(' ');
return (
<li className={classArr}>
<span>{props.name}</span>
<span>{props.date}</span>
<span>{props.amount}</span>
<Button click={props.delete} btnType="Delete">Delete</Button>
</li>
)
};
export default Merchant;
</code></pre>
<p>In addition there is a ReviewsContainer with the same structure of MerchantContainer but for a list of reviews (with a Review container with the same structure of Merchant).</p>
<p>Now I want to create a Summary component </p>
<pre><code>const Summary = props => {
return (
<div>
<MerchantContainer />
<ReviewsContainer />
</div>
);
}
</code></pre>
<p>And use a Switch Component in App.js</p>
<pre><code><Switch>
<Route path="/merchants" component={MerchantContainer} />
<Route path="/reviews" component={ReviewsContainer} />
<Route path="/summary" component={Summary} />
</Switch>
</code></pre>
<p>It is ok to use a "dumb" component for the Summary component? Or do I have to restructure so the Summary is the only container and MerchantContainer and ReviewsContainer must work with props from Summary?</p>
<p>One of the other features is a Dashboard component that will include the Summary and other components (is still not defined in the requirements for this task). So this dilemma will be repeated.</p>
| [] | [
{
"body": "<p>In my opinion (which also aligns with the <a href=\"https://redux.js.org/faq/react-redux#should-i-only-connect-my-top-component-or-can-i-connect-multiple-components-in-my-tree\" rel=\"nofollow noreferrer\">official Redux FAQ (\"Should I only connect my top component, or can I connect multiple components in my tree?\")</a>:</p>\n\n<ul>\n<li>If <code>MerchantContainer</code> and <code>ReviewContainer</code> use mostly the same state or actions, you could reduce duplication by having a common container for both of those.</li>\n<li>If <code>MerchantContainer</code> and <code>ReviewContainer</code> don't have any state in common (which I think is the case here), there's no real value in having <code>Summary</code> as a common container. Quite the oppositive: If you'd make <code>Summary</code> the common container, <code>Summary</code> would have access to state and actions that <code>Summary</code> doesn't care about at all.</li>\n</ul>\n\n<p>To summarize: It's perfectly fine to have multiple connected components that might be children of a \"dumb\" component. If you have a similar setup in a couple of the children, you might consider extracting a common container.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T11:03:14.590",
"Id": "409023",
"Score": "0",
"body": "Yes, I'm trying to do just like you said, but sometimes planning the structure for the app is really tough, it's like a thin line between \"too much information for this container\" and \"not a container\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T11:36:22.783",
"Id": "409025",
"Score": "0",
"body": "That’s true. Experience helps with deciding between these two. But you’ll never get it perfect all the time at the first try. It helped me to consider designs as flexible that might and should change when I know more about the software (even if my reasoning was sound previously)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T01:12:08.450",
"Id": "211512",
"ParentId": "211490",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211512",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T16:46:08.763",
"Id": "211490",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"redux"
],
"Title": "Summary page with react-redux: container or presentational component"
} | 211490 |
<p>I'm an engineer working with a deformable membrane that is attached to actuators. The goal is to move the membrane from one shape to another, without ripping the membrane. This imposes "neighbor rules" which state the maximum deviation between neighboring actuators cannot exceed some value, or the membrane will rip.</p>
<p>For the purposes of the problem, let's consider a 1-d membrane or "rope" that is attached to actuators:</p>
<p><a href="https://i.stack.imgur.com/r87x3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/r87x3.png" alt="enter image description here"></a></p>
<p><strong>The goal is to move the rope from one set of actuator positions to another in the minimum number of moves.</strong></p>
<p>The rules are</p>
<ol>
<li>Only one actuator may be moved at a time</li>
<li>An actuator may be moved any distance, but </li>
<li>An actuator must respect the neighbor rule, so the distance between it and subsequent actuators cannot exceed a fixed distance</li>
</ol>
<p>The code below presents two algorithms, neither of which is optimal. The first algorithm, <code>get_max_deviation_index</code> picks the actuator which is furthest from its final position, then moves it the maximum distance possible. This algorithm gets stuck on a simple test of moving from position [2, 4, 6, 3] to [-2, -4, -6, -3]. The next algorithm, <code>get_next_index</code>, starts at the first actuator, moves it the maximum distance possible, and then moves to the subsequent actuator and does the same, until it is converged. This algorithm works, but I do not believe it is optimal.</p>
<p>The code below implements both algorithms; please comment in/out the line beginning with <code>ind =</code> to switch between them. My question is:</p>
<p><strong>What is the optimal algorithm to move between one position and another?</strong></p>
<pre><code>import numpy as np
def check_legal(y, max_dist=None):
#checks if a position is legal
return np.all(np.diff(y)<=max_dist)
def get_neighbors(index, array):
#gets neighbors of an element in a list,
#respecting end nodes
max_index = len(array)-1
if index == 0:
neighbors = [array[index+ 1]]
elif index == max_index:
neighbors = [array[index- 1]]
else:
neighbors = list(array[[index-1, index + 1]])
return neighbors
def get_max_deviation_index(current_pos, final):
diff = np.abs(final-current_pos)
max_ind = np.where(diff == np.max(diff))[0][0]
#find move amt necessary to get to final position
return max_ind
def get_next_index(current_pos, current_ind):
if current_ind == len(current_pos)-1:
next_ind = 0
else:
next_ind = current_ind+1
return next_ind
def solve(init, final, max_dist=None):
assert check_legal(init, max_dist=max_dist)
assert check_legal(final, max_dist=max_dist)
assert len(init) == len(final)
print init
current_pos = init
idx = 0
ind = 0
while not np.allclose(current_pos, final):
#find index that has maximum offset from where it should be
#ind = get_max_deviation_index(current_pos, final)
ind = get_next_index(current_pos, ind)
delta = final[ind]-current_pos[ind]
if delta == 0:
continue
sign = np.sign(delta)
#find neighbors of that point
neighbors = get_neighbors(ind, current_pos)
#find the maximum allowable move
pos_options = [final[ind]]\
+[n+sign*max_dist for n in neighbors]
if sign<0:
move = max(pos_options)
else:
move = min(pos_options)
current_pos[ind] = move
print current_pos
idx+=1
return idx
if __name__ == "__main__":
initial_state = np.array([2,4,6, 3])
final_state = -initial_state
max_dist = 3 #max distance between neighboring actuators
ans = solve(initial_state, final_state, max_dist=max_dist)
print "Completed in ", ans, " moves"
</code></pre>
| [] | [
{
"body": "<p>Your bolded question <strong><em>What is the optimal algorithm</em></strong> is off-topic for Code Review. If you're really interested in original-research answers to that question, I think it might plausibly be on-topic for <a href=\"https://puzzling.stackexchange.com/help/on-topic\">Puzzling SE</a> or <a href=\"https://cs.stackexchange.com/help/on-topic\">Computer Science SE</a>.</p>\n\n<p>Certainly if you post in either of those places, looking for \"optimal\" algorithms, you will have to define what you mean by \"optimal.\" The simplest way of doing that would also be useful on CodeReview — and also in general in your programming career! <strong>Provide test cases.</strong></p>\n\n<pre><code>assert solve([2, 4, 6, 3], [-2, -4, -6, -3], 3) == 42\n</code></pre>\n\n<p>This test case was constructed by looking at your sample program and then filling in an utterly random number <code>42</code> in the one place that matters. When you post the question elsewhere (and/or here again), make sure to have that number filled in.\nAnd then give some other test cases!</p>\n\n<pre><code>assert solve([2, 4, 6, 3], [-2, -4, -6, -3], float('inf')) == 4\nassert solve([1, 1, 1], [0, 0, 0], 1) == 3\n</code></pre>\n\n<p>And then consider what should happen in cases of \"invalid input\":</p>\n\n<pre><code>assert solve([1, 1, 1], [0, 0, 0], 0) is None\nassert solve([1, 2, 1], [1, 3, 1], 1) is None\nassert solve([1, 3, 1], [1, 2, 1], 1) is None\nassert solve([1, 3, 1], [1, 3, 1], 1) is None\n</code></pre>\n\n<hr>\n\n<p>On your code itself, try to write out full identifiers instead of abbreviations: <code>index</code> (index of what?) instead of <code>ind</code>, for example.</p>\n\n<p>When writing a \"predicate\" function that returns <code>bool</code>, give it a name that indicates the <em>predicate</em>, rather than an action verb: instead of <code>check_legal</code> (which should really be <code>check_legality</code>), prefer <code>is_legal</code>, so that you can write</p>\n\n<pre><code>assert is_legal(init, max_dist)\n</code></pre>\n\n<p>Notice that <code>max_dist</code> has no reason to be a keyword argument, and no reason to be optional. Instead of passing <code>None</code> and special-casing it, just pass <code>float('inf')</code> and <em>don't</em> write any special cases.</p>\n\n<hr>\n\n<pre><code>pos_options = [final[ind]]\\\n +[n+sign*max_dist for n in neighbors]\n</code></pre>\n\n<p>This line of code is impenetrable, due to the lack of whitespace and the backslash in the middle. I'd at least recommend</p>\n\n<pre><code>pos_options = [final[ind]] + [n + sign * max_dist for n in neighbors]\n</code></pre>\n\n<p>and then look for a way to refactor that or at least put a code comment explaining the logic behind the expression.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T23:40:01.200",
"Id": "211505",
"ParentId": "211492",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T17:27:27.707",
"Id": "211492",
"Score": "6",
"Tags": [
"python",
"algorithm",
"numpy",
"computational-geometry",
"pathfinding"
],
"Title": "Optimal algorithm to move a a rope from one position to another"
} | 211492 |
<p>This is an image representation of my code below:</p>
<p><a href="https://i.stack.imgur.com/vNOgM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vNOgM.png" alt="enter image description here"></a></p>
<p>This is what they do:</p>
<p><strong>CellWithImageX</strong>: Subclasses of <code>UITableViewCell</code>. They have an image and an loading indicator. Only 1 can be shown at the time.</p>
<p><strong>ImageRequester</strong>: Downloads the images and gives <code>ImageCache</code> a callback when it's done.</p>
<p><strong>FileExplorer</strong>: Saves the images.</p>
<p><strong>ImageCache</strong>: Manages everything. Since I am most concerned about the current design, I think the code for the <code>ImageCache</code> is only relevant:</p>
<pre><code>// Used to weakly hold the CellWithImageX image classes. (Is this bad?)
open class WeakObjectWrapper<T: AnyObject> {
public weak var obj: T?
public init(obj: T) {
self.obj = obj
}
}
class ImageCache {
// I can not understand how it can work if it isn't a singleton.
// From every cell, I can easily pass the reference without to much hassle.
// I am not sure for an singleton alternative.
static let sharedInstance = ImageCache()
// TODO: Maybe remove some elements from time to time?
// Yes, this is an array of the images in the table view cell...
private var loadableImages: [WeakObjectWrapper<LoadableImage>] = []
private init() {}
func handleImage(photoIdentifier: Int64, loadableImage: LoadableImage) {
// Bit concenered about a race condition.
// I read about DispatchQueues and Semaphores, can't really
// decide what would be the best way.
assert(Thread.isMainThread)
// LoadableImage has an identifier which we can use to later on match the downloaded image.
loadableImage.identifier = photoIdentifier
guard photoIdentifier != 0 else {
loadableImage.show(image: #imageLiteral(resourceName: "anonymous"))
return
}
guard let image = determineImage(photoIdentifier: photoIdentifier) else {
loadableImages.append(WeakObjectWrapper(obj: loadableImage))
loadableImage.showIndicator()
return
}
loadableImage.show(image: image)
}
func received(image: UIImage, forPhotoIdentifier: Int64) {
assert(Thread.isMainThread)
FileExplorer.sharedInstance.save(image: image.pngData()!, photoIdentifier: forPhotoIdentifier) // This is validated that this works, we can safely force unwrap.
for loadableImage in loadableImages.filter({ $0.obj?.identifier == forPhotoIdentifier }) {
// While iterating it may occur that the reference is gone.
loadableImage.obj?.show(image: image)
}
}
private func determineImage(photoIdentifier: Int64) -> UIImage? {
guard let image = FileExplorer.sharedInstance.determineImage(photoIdentifier: photoIdentifier) else {
ImageRequester.sharedInstance.download(photoIdentifier: photoIdentifier)
return nil
}
return image
}
}
</code></pre>
<p>In my <code>cellForRowAt</code> method in my <code>tableView</code>, I am calling the <code>ImageCache</code> handleImage method on my <code>cell.loadableImage</code> property.</p>
<p>My concerns:</p>
<ul>
<li>I am using a few singletons: ImageRequester, ImageCache and
FileExplorer. I am not sure if this is the best approach, but I can
not imagine a better way because this way, all my cells can easily
register themselfs. </li>
<li>I have a array of weak objects which references
to the loadable images inside of a tableViewCell. Isn't there a
better way?</li>
<li>I am asserting I am on the main thread. If I am on multiple threads, race conditions may occur while I loop through the array. I looked into DispatchQueues and Semaphores. I just didn't found the right way to do it, and what the best way would be in my case. Does someone has a suggestion about what way would be a good way in my case?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T06:30:31.063",
"Id": "432717",
"Score": "0",
"body": "A tableView can reuse cells. This means what in some cases (for example in case of bad internet connection) ImageCache can set wrong images into reused cells. I think you can think about support of cancellation of images delivery."
}
] | [
{
"body": "<p>The way I see it your requirements can be summarized as:</p>\n\n<ol>\n<li>Have a central repository of images.</li>\n<li>Load Images from a some data source.</li>\n<li>Save Persist Images.</li>\n<li>Give a cell its appropriate image based on an identifier.</li>\n</ol>\n\n<p>The main issue I see is that the cells are tightly coupled to the ImageCache object, it might be better to have some sort of ViewModel or controller layer sit between your image cache and cells. This model or controller would contain the information needed to retrieve an image for image cache along with the information needed to display the image to the cell. This would make your code much more testable and decouple your UITableViewCells from the the your singleton cache.</p>\n\n<p>On whether a singleton is necessary-- I am going to take a guess that this is all for one ViewController. Why not just initialize the ImageCache object in that ViewController? If this is truly used across many ViewControllers than I could maybe be convinced to get behind the use of a singleton.</p>\n\n<p>On the WeakReference array... that is valid and actually relatively advanced pattern in Swift, I'm not sure that you really need it here though although its a little hard to tell without more context. It appears LoadableImage is some sort of object that encapsulates a callback that displays the image or an indicator on the UI... in which case yes you would need a weak reference, although I am unsure as to why you even need to store the LoadableImages in an array to begin with. I think that you could abstract away the array if you refactored to a more traditional Callback oriented approach.</p>\n\n<p>In a callback approach the TableViewCells would merely request the appropriate image and show the loading indicator until the callback was called. If you really needed to cache the images, you could do so in an array within the cache. </p>\n\n<p>I wish that your method names were more descriptive in Swift style... for example determineImage(for photoId:String). That's part of the expressiveness and readability of the language. Another example the function received doesn't really express what it's use is I think that its some sort of callback that will display an image once it has been loaded and display that image to a specific LoadableImage, but this needs to be more clear.</p>\n\n<p>I think to give you more advice you need to post more code, along with a description of what the requirements are. For example: How many ViewControllers are using the Cache? Do you need to store images across the lifecycle of multiple ViewControllers? How are you planning on linking the ImageIdentifiers to the TableViewCells.</p>\n\n<p>If you post a few more details, I will follow up with a few code samples, but as it is I don't see how I can give you any tangible direction without knowing a little bit more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T16:39:22.723",
"Id": "223156",
"ParentId": "211498",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T20:56:11.460",
"Id": "211498",
"Score": "3",
"Tags": [
"image",
"swift"
],
"Title": "Design pattern: image downloads"
} | 211498 |
<p>I have only recently started learning python and the below is my attempt to create an 'interest rate' object which, given one of several types of interest/discount rate, gives the user access to all of the other corresponding rates that are equivalent to this. This looks as follows:</p>
<pre><code>import math
class InterestRate:
def __init__(self, effectiveInterestRate=0, nominalInterestRate=0, effectiveDiscountRate=0, nominalDiscountRate=0, discountFactor=0, forceOfInterest=0, paymentsPerPeriod=1):
self.effectiveInterestRate = effectiveInterestRate
self.nominalInterestRate = nominalInterestRate
self.effectiveDiscountRate = effectiveDiscountRate
self.nominalDiscountRate = nominalDiscountRate
self.discountFactor = discountFactor
self.forceOfInterest = forceOfInterest
self.paymentsPerPeriod = paymentsPerPeriod
numberOfRatesProvided = 0
for attr, value in vars(self).items():
if value != 0 and attr != 'paymentsPerPeriod':
numberOfRatesProvided += 1
rateGiven = attr
if numberOfRatesProvided != 1:
raise Exception("Incorrect number of inputs passed to InterestRate object")
if rateGiven == 'nominalInterestRate': self.effectiveInterestRate = (nominalInterestRate/paymentsPerPeriod + 1)**paymentsPerPeriod - 1
elif rateGiven == 'effectiveDiscountRate': self.effectiveInterestRate = effectiveDiscountRate / (1 - effectiveDiscountRate)
elif rateGiven == 'nominalDiscountRate': self.effectiveInterestRate = (1 - nominalDiscountRate/paymentsPerPeriod)**-paymentsPerPeriod - 1
elif rateGiven == 'discountFactor': self.effectiveInterestRate = 1/discountFactor - 1
elif rateGiven == 'forceOfInterest': self.effectiveInterestRate = math.exp(forceOfInterest) - 1
self.nominalInterestRate = self.paymentsPerPeriod*((1+self.effectiveInterestRate)**(1/self.paymentsPerPeriod) - 1)
self.effectiveDiscountRate = self.effectiveInterestRate/(1+self.effectiveInterestRate)
self.nominalDiscountRate = self.paymentsPerPeriod*(1 - (1 + self.effectiveInterestRate)**(-1/self.paymentsPerPeriod))
self.discountFactor = 1 / (1 + self.effectiveInterestRate)
self.forceOfInterest = math.log(1 + self.effectiveInterestRate)
def outputInterestRateData(self):
print("\n ----------------------------------------------------")
print(" Interest Rate Data ")
print(" ----------------------------------------------------")
print(" Payments per Period: ", self.paymentsPerPeriod)
print(" Effective Interest Rate: ", self.effectiveInterestRate)
print(" Effective Discount Rate: ", self.effectiveDiscountRate)
print(" Nominal Interest Rate: ", self.nominalInterestRate)
print(" Nominal Discount Rate: ", self.nominalDiscountRate)
print(" Discount Factor: ", self.discountFactor)
print(" Force Of Interest: ", self.forceOfInterest)
print(" ----------------------------------------------------")
def shiftedPaymentPV(paymentAmmount, periodsShifted):
return paymentAmmount*(1 + self.effectiveInterestRate)**periodsShifted
</code></pre>
<p>Assuming that it is clear enough what I have attempted to do here, can anyone offer some constructive criticism on my first attempt at a python class module?</p>
| [] | [
{
"body": "<p><strong>Trying to use the code</strong></p>\n\n<p>The class defines something which feels a bit weird to use. We'll see a few ways to improve this.</p>\n\n<p>The constructor provides default value for all parameters which leads one to think he can just do <code>r = InterestRate()</code> and enjoy. It is most definitly not the case because one (and only one) of the inputs must be provided.</p>\n\n<p>This suggests that maybe we should not have a single constructor doing many things but many small constructors (using <a href=\"https://code-maven.com/slides/python-programming/class-methods-alternative-constructor\" rel=\"nofollow noreferrer\">alternative constructors for example</a>).</p>\n\n<p>Then, trying to use the <code>shiftedPaymentPV</code> method, I stumbled on a different error: the <code>self</code> is not part of the signature which makes it unusable as far as I can tell.</p>\n\n<p><strong>Simplifying the code</strong></p>\n\n<p>In the <code>__init__</code>, we set the <code>paymentsPerPeriod</code> attribute only to excluse it in next operation when handling all attributes. We may as well set it afterward to makes things more simple.</p>\n\n<p>This also shows how subtle and fragile that piece of logic is. One could easily break the whole thing by moving an attribute which doesn't seem to be used because we use introspection magic (which is pretty cool in itself but probably better to avoid here).</p>\n\n<p>Let's see how it can be improved anyway.</p>\n\n<p>Instead of counting elements as we go, we could put them in a list and count them afterwards. This helps if we want to show the list to the user in the exception message.</p>\n\n<pre><code> ratesGiven = [attr for attr, value in vars(self).items() if value != 0 and attr != 'paymentsPerPeriod']\n if len(ratesGiven) != 1:\n raise Exception(\"Incorrect number of inputs passed to InterestRate object\")\n rateGiven = ratesGiven[0]\n</code></pre>\n\n<p>This could give use the following code:</p>\n\n<pre><code>import math\n\nclass InterestRate:\n\n @classmethod\n def from_nominal(cls, nominalInterestRate, paymentsPerPeriod=1):\n effectiveInterestRate = (nominalInterestRate/paymentsPerPeriod + 1) ** paymentsPerPeriod - 1\n return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)\n\n @classmethod\n def from_effective_discount_rate(cls, effectiveDiscountRate, paymentsPerPeriod=1):\n effectiveInterestRate = effectiveDiscountRate / (1 - effectiveDiscountRate)\n return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)\n\n @classmethod\n def from_nominal_discount_rate(cls, nominalDiscountRate, paymentsPerPeriod=1):\n effectiveInterestRate = (1 - nominalDiscountRate/paymentsPerPeriod) ** -paymentsPerPeriod - 1\n return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)\n\n @classmethod\n def from_discount_factor(cls, discountFactor, paymentsPerPeriod=1):\n effectiveInterestRate = 1 / discountFactor - 1\n return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)\n\n @classmethod\n def from_force_of_interest(cls, forceOfInterest, paymentsPerPeriod=1):\n effectiveInterestRate = math.exp(forceOfInterest) - 1\n return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)\n\n @classmethod\n def from_effective_interest_rate(cls, effectiveInterestRate, paymentsPerPeriod=1):\n return cls(effectiveInterestRate=effectiveInterestRate, paymentsPerPeriod=paymentsPerPeriod)\n\n def __init__(self, effectiveInterestRate, paymentsPerPeriod):\n self.effectiveInterestRate = effectiveInterestRate\n self.paymentsPerPeriod = paymentsPerPeriod\n\n self.nominalInterestRate = paymentsPerPeriod * ((1 + effectiveInterestRate) ** (1 / paymentsPerPeriod) - 1)\n self.effectiveDiscountRate = effectiveInterestRate / (1 + effectiveInterestRate)\n self.nominalDiscountRate = paymentsPerPeriod * (1 - (1 + effectiveInterestRate) ** (-1 / paymentsPerPeriod))\n self.discountFactor = 1 / (1 + effectiveInterestRate)\n self.forceOfInterest = math.log(1 + effectiveInterestRate)\n\n def outputInterestRateData(self):\n print(\"\\n ----------------------------------------------------\")\n print(\" Interest Rate Data \")\n print(\" ----------------------------------------------------\")\n print(\" Payments per Period: \", self.paymentsPerPeriod)\n print(\" Effective Interest Rate: \", self.effectiveInterestRate)\n print(\" Effective Discount Rate: \", self.effectiveDiscountRate)\n print(\" Nominal Interest Rate: \", self.nominalInterestRate)\n print(\" Nominal Discount Rate: \", self.nominalDiscountRate)\n print(\" Discount Factor: \", self.discountFactor)\n print(\" Force Of Interest: \", self.forceOfInterest)\n print(\" ----------------------------------------------------\")\n\n def shiftedPaymentPV(paymentAmmount, periodsShifted):\n assert False, \"this can't work\"\n return paymentAmmount*(1 + self.effectiveInterestRate)**periodsShifted\n\n\nr = InterestRate.from_nominal(nominalInterestRate=-0.9375, paymentsPerPeriod=2)\nprint(r.outputInterestRateData())\n</code></pre>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide called PEP 8</a>. It is definitly worth reading it and trying to apply it.</p>\n\n<p>In your case, that would mean adding whitespaces around operators and using the <code>snake_case</code> naming convention for variables and method names.</p>\n\n<p><strong>String conversions</strong></p>\n\n<p>Instead of a <code>outputInterestRateData</code>, maybe you could define the <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__str__\" rel=\"nofollow noreferrer\"><code>__str__</code></a> method.</p>\n\n<p>Also, you could take this chance to use one of the <a href=\"https://pyformat.info/\" rel=\"nofollow noreferrer\">various ways to format strings in Python</a>.</p>\n\n<p>You'd get something like:</p>\n\n<pre><code> def __str__(self):\n return \"\"\"\n ----------------------------------------------------\n Interest Rate Data \n ----------------------------------------------------\n Payments per Period: {} \n Effective Interest Rate: {} \n Effective Discount Rate: {} \n Nominal Interest Rate: {} \n Nominal Discount Rate: {} \n Discount Factor: {} \n Force Of Interest: {} \n ----------------------------------------------------\n \"\"\".format(self.paymentsPerPeriod, self.effectiveInterestRate,\n self.effectiveDiscountRate, self.nominalInterestRate,\n self.nominalDiscountRate, self.discountFactor,\n self.forceOfInterest)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T00:00:45.863",
"Id": "409116",
"Score": "0",
"body": "Thank you for your in-depth response."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T22:31:33.710",
"Id": "211500",
"ParentId": "211499",
"Score": "3"
}
},
{
"body": "<p>Starting from the excellent progress @Josay made, I'd only have one major suggestion: Turn the set-once properties into read-only, computed properties. This will:</p>\n\n<ol>\n<li>prevent them from being inadvertently overwritten by other code and</li>\n<li>allow the <code>effectiInterestRate</code> and/or <code>paymentsPerPeriod</code> to be updated, without the derived computations then becoming invalid.</li>\n</ol>\n\n<p>The main change is to make the constructor be:</p>\n\n<pre><code> def __init__(self, effectiveInterestRate, paymentsPerPeriod):\n self.effectiveInterestRate = effectiveInterestRate\n self.paymentsPerPeriod = paymentsPerPeriod\n</code></pre>\n\n<p>and then make some computed properties:</p>\n\n<pre><code> @property\n def nominalInterestRate(self):\n return self.paymentsPerPeriod * ((1 + self.effectiveInterestRate) ** (1 / self.paymentsPerPeriod) - 1)\n\n @property\n def effectiveDiscountRate(self):\n return self.effectiveInterestRate / (1 + self.effectiveInterestRate)\n\n @property\n def nominalDiscountRate(self):\n return self.paymentsPerPeriod * (1 - (1 + self.effectiveInterestRate) ** (-1 / self.paymentsPerPeriod))\n\n @property\n def discountFactor(self):\n return 1 / (1 + self.effectiveInterestRate)\n\n @property\n def forceOfInterest(self):\n return math.log(1 + effectiveInterestRate)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T11:42:16.533",
"Id": "409183",
"Score": "0",
"body": "Thanks! I was completely oblivious to the existence of '@property'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:24:12.840",
"Id": "409226",
"Score": "0",
"body": "Excellent point!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T03:18:26.453",
"Id": "211594",
"ParentId": "211499",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T21:30:12.393",
"Id": "211499",
"Score": "0",
"Tags": [
"python",
"finance"
],
"Title": "Python 'interest rate' object"
} | 211499 |
<p>I recently did problem <em>1.7 Rotate Matrix</em> in <em>Cracking the Coding Interview</em>. I realized my code is very different than what is in the book and also from what I'm finding online (I'm having trouble following the code in the book). I just want to know if the code I wrote would be appropriate in an interview setting or would I be expected to write code like the solution in the book.</p>
<p>The problem states</p>
<blockquote>
<p>Rotate Matrix: Given an image represented by an N×N matrix, where each
pixel in the image is 4 bytes, write a method to rotate the image by
90 degrees. Can you do this in place?</p>
</blockquote>
<p>Here is my code:</p>
<pre><code>def transpose(the_array):
res = []
for i in range(len(the_array)):
transposed = []
for col in the_array:
transposed.append(col[i])
transposed.reverse()
res.append(transposed)
return res
print(transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
</code></pre>
<p>Also, would the <code>reverse</code> method be ok to use in an interview?</p>
<p>I just realized my solution may not be considered in place.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T07:08:11.463",
"Id": "480391",
"Score": "0",
"body": "@l0b0 Probably chapter number."
}
] | [
{
"body": "<blockquote>\n <p>I just want to know if the code I wrote would be appropriate in a interview setting or would I expect to write code like the solution in the book.</p>\n</blockquote>\n\n<p>As we cannot see the solution form the book, this is hard for us to answer.</p>\n\n<p>Your solution seems to work which is ok for learning purposes, the biggest I can think of with your current code is <a href=\"https://www.python.org/dev/peps/pep-0202/\" rel=\"nofollow noreferrer\">List comprehension</a>.</p>\n\n<blockquote>\n<pre><code>for col in the_array:\n transposed.append(col[i])\ntransposed.reverse()\n</code></pre>\n</blockquote>\n\n<p>Could be </p>\n\n<pre><code>transposed = [col[i] for col in the_array][::-1]\n</code></pre>\n\n<p><em>Note how instead of <code>.reverse()</code> I use the slice annotation to reverse the list <code>[::-1]</code></em></p>\n\n<p>We could even make the first for loop another list comprehension (essentially creating a double list comprehension)</p>\n\n<pre><code>def transpose2(the_array):\n return [\n [col[i] for col in the_array][::-1]\n for i in range(len(the_array))\n ]\n</code></pre>\n\n<p>I should note though that is is a rather elaborate way of writing</p>\n\n<pre><code>def transpose3(arr):\n return zip(*arr[::-1])\n</code></pre>\n\n<p>Where the <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> rotates the reversed list with <a href=\"https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists\" rel=\"nofollow noreferrer\">argument unpacking</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:56:06.723",
"Id": "211529",
"ParentId": "211501",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T22:42:23.917",
"Id": "211501",
"Score": "2",
"Tags": [
"python",
"algorithm",
"array",
"interview-questions",
"matrix"
],
"Title": "Rotate matrix 90 degrees"
} | 211501 |
<p>I was wondering if I could solve the problem <a href="https://codegolf.stackexchange.com/questions/173189/display-numbers-lacking-2s">here</a> (mostly unrelated) using only simple binary operators since it is just mapping 100 different inputs to a boolean. For this I wrote this, but I have no real way to test, and I was also hoping it could be faster.</p>
<pre><code>#include <iostream>
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX_VAL 100
bool CODES[] = {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1};
int op(int a, int b, int index) {
switch (index) {
case 0: return a + b; break;
case 1: return a - b; break;
case 2: return a * b; break;
case 3: return a / b; break;
case 4: return a & b; break;
case 5: return a | b; break;
case 6: return a ^ b; break;
case 7: return a % b; break;
}
}
int main(int argc, char const *argv[]) {
for (int A=1; A < 2; A++) {
std::cout << A << std::endl;
for (int B=1; B < 2; B++) {
std::cout << A << " " << B << std::endl;
for (int C=1; C < 2; C++) {
for (int D=1; D < MAX_VAL; D++) {
std::cout << A << " " << B << " " << C << " " << D << std::endl;
for (int E=1; E < MAX_VAL; E++) {
for (int opA = 0; opA < 8; opA++) {
for (int opB = 0; opB < 8; opB++) {
for (int opC = 0; opC < 8; opC++) {
for (int opD = 0; opD < 8; opD++) {
for (int opE = 0; opE < 8; opE++) {
bool good = true;
int index = 1;
for (bool item : CODES) {
int val = op(index, A, opA);
val = op(val, B, opB);
val = op(val, C, opC);
val = op(val, D, opD);
val = op(val, E, opE);
val &= 1;
if (val != item) {
good = false;
break;
}
index++;
}
if (good) {
std::cout<<"GOOD "<<A<<" "<<opA<<" "<<B<<" "<<opB<<" "<<C<<" "<<opC<<" "<<D<<" "<<opD<<" "<<E<<" "<<opE<<std::endl;
}
}
}
}
}
}
}
}
}
}
}
return 0;
}
</code></pre>
<p>I am specifically looking for help for optimization, but of course style, correctness, or anything else is much appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:51:23.443",
"Id": "409017",
"Score": "0",
"body": "Could you summarize the puzzle for us? A link simply titled \"here\" isn't as good as a proper description. Thanks."
}
] | [
{
"body": "<p>Before we even get started into optimizations, I would like to point out a couple of things. First- <strong>many</strong> permutations of operands + operators are going to behave identically. There isn't a whole lot we can do to skip these, but in practice it seems that \"similar\" permutations are composed of \"similar\" components. That is, a handful of permutations of operands + operators that differ by 1 operand or operator will often have very similar input->output mappings. Some times you can take advantage of this to speedup your search. Sometimes the best solution is to do a completely random search of permutations to avoid the problem completely (at the cost of trying duplicate permutations). I won't explore either option below, but I wanted to mention them for completeness.</p>\n\n<p>Secondly, you are trying to create a (int->bool) input->output mapping for 100 unique values. Even if we never tried two permutations of operands + operators that produce the same mapping, there's still 2^100 unique mappings to explore. That is not something that we can reasonably brute force. For 5 operands chosen (with replacement) from your 8 and 5 constants each in the range [0-99] inclusive, we have <code>8^5 * 100^5 == 3.27*10^14 == 2^48</code> permutations. Unless we are astronomically lucky, you're going to need to at least double your operand + argument count anyways. We need something smarter.</p>\n\n<p>We need to try to prune the search space, but in order to do that we need to be able to determine early on whether a permutations is worth pursing. In the process of restructuring your code to support such a heuristic, we're also going to gain a small performance boost. The following line of code is executed over and over for all 100 indices, and isn't going to change when you change <code>opB</code>, <code>opC</code>, and so on.</p>\n\n<pre><code>int val = op(index, A, opA);\n</code></pre>\n\n<p>This logic also applies to <code>val = op(val, B, opB);</code>, and the others. This isn't too bad- you're only losing a factor of 5 in performance, but it needs to be changed anyways to give our algorithm some foresight. We can reorder your loops to put the argument and operand together, and then compute the intermediate values immediately-</p>\n\n<pre><code>for (int A=1; A < 2; A++) {\n std::cout << A << std::endl;\n for (int opA = 0; opA < 8; opA++) {\n int valA[100];\n // compute val for all indices\n // Loop over B, C, D\n</code></pre>\n\n<p>This will allow us to compute the intermediate value of <code>val</code> exactly once- every time it is changed, rather than every time we change <em>any</em> operand / operator.</p>\n\n<p>Now how does this help us prune the search space? Notice that for any mapping our operand constant is... constant. Together with the operator, they make a new (unary) operator. We can take this further as well- since all our new operators are \"chained\" together, they can be seen as one big (unary) operator.</p>\n\n<pre><code>input <operator> <operand_constant> => output\ninput <new_operator> output\n...\ninput <new_operator_A> <new_operator_B> => output\ninput <combined_operator> => output\n</code></pre>\n\n<p>The <code>index</code> itself is the only input and each index is unique, but each intermediate value/output might not be unique. Regardless of the <code>index</code> value, if two intermediate operations produce the same intermediate value, then both will produce the same output value. We can use this to prune the search space. </p>\n\n<p>If two values in the array are identical, then their corresponding bits in the original array must both be the same. If they are not, immediately attempt the next operator / operand value. If you reduce your computations to unsigned chars spanning <code>[0, 255]</code> inclusive, the probability of having two equal intermediate values is roughly <code>0.999999999827</code>. There will likely be <em>many</em> intermediate values with the same value, allowing you to quickly prune bad branches in the search tree.</p>\n\n<p>To quickly determine if two values in the array cause a conflict, use an external array of size 256. When you compute an intermediate value <code>v</code>, check that <code>array[v]</code> is either uninitialized, or matches the desired output (map 0->1 and 1->2 maybe, and leave 0 to indicate uninitialized) and set the array element accordingly. If it doesn't match, then there's a conflict.</p>\n\n<p>You could probably optimize this further by using a linked list to store the unique values of the array (every time <code>array[v]</code> is uninitialized), and then only check that those values are correct- avoiding redundant computations. </p>\n\n<p>Even with this pruning, I suspect this will probably still be intractable. 2^100 is a <em>huge</em> number. You'll likely need to find a second way to check for \"dead-end\" branches, and/or an algorithmic breakthrough.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T03:35:16.673",
"Id": "211516",
"ParentId": "211503",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T23:18:03.360",
"Id": "211503",
"Score": "0",
"Tags": [
"c++",
"performance"
],
"Title": "Operator Search for Puzzle"
} | 211503 |
<p>I am solving the <a href="https://open.kattis.com/problems/primereduction" rel="nofollow noreferrer">Prime Reduction challenge on Kattis</a>.</p>
<blockquote>
<p>Consider the following process, which we’ll call prime reduction. Given an input <em>x</em>:</p>
<ol>
<li>if <em>x</em> is prime, print <em>x</em> and stop</li>
<li>factor <em>x</em> into its prime factors <em>p<sub>1</sub>, p<sub>2</sub>, …, p<sub>k</sub></em></li>
<li>let <em>x</em> = <em>p</em><sub>1</sub> + <em>p</em><sub>2</sub> + ⋯ + <em>p<sub>k</sub></em></li>
<li>go back to step 1</li>
</ol>
<p>Write a program that implements prime reduction.</p>
<h3>Input</h3>
<p>Input consists of a sequence of up to 20000 integers, one per line, in the range 2 to 10<sup>9</sup>. The number 4 will not be included in the sequence (try it to see why it’s excluded). Input ends with a line containing only the number 4.</p>
<h3>Output</h3>
<p>For each integer, print the value produced by prime reduction executed on that input, followed by the number of times the first line of the process executed.</p>
</blockquote>
<p>I have already solved it using Java. Now I am trying to solve it in python. My code did well on the sample tests, but on the second test my code fails due to time limit exceeded.</p>
<p>Someone could tell me what I did wrong?</p>
<p>My python code:</p>
<pre><code>import sys
from math import sqrt, floor
def is_prime_number(number):
if number == 2:
return True
if number % 2 == 0:
return False
return not any(number % divisor == 0 for divisor in range(3, floor(sqrt(number)) + 1, 2))
def sum_prime_factors(number):
factors = 0
while number % 2 == 0:
factors += 2
number = floor(number / 2)
if is_prime_number(number):
factors += number
return factors
for factor in range(3, floor(sqrt(number)) + 1, 2):
if is_prime_number(factor):
while number % factor == 0:
factors += factor
number = number / factor
if number == 1:
return factors
factors += number
return factors
def print_output(x, i):
if is_prime_number(x):
print(x, i)
return
i = i + 1
factors = sum_prime_factors(x)
print_output(factors, i )
[print_output(item, 1) for item in map(int, sys.stdin) if item != 4]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:35:54.203",
"Id": "409107",
"Score": "2",
"body": "Welcome to Code Review. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. I've rolled your question back to its previous version, see its [revisions](https://codereview.stackexchange.com/posts/211504/revisions)."
}
] | [
{
"body": "<p>Some ideas:</p>\n\n<ul>\n<li><code>is_prime_number</code> doesn't scale well when dealing with bigger primes - the range of odd numbers 3..sqrt(number) is going to get very big. You'd be better off implementing a more sophisticated algorithm such as <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Eratosthenes' Sieve</a>, where the cost of checking primality of subsequent primes grows slower.</li>\n<li><code>sum_prime_factors</code> duplicates the implementation of primality checking from <code>is_prime_number</code>.</li>\n<li><p><code>[print_output(item, 1) for item in map(int, sys.stdin) if item != 4]</code> is awkward. I would use a <code>main</code> method and any of the common</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>patterns for making the code reusable and testable.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T00:52:01.660",
"Id": "211508",
"ParentId": "211504",
"Score": "1"
}
},
{
"body": "<h2>Efficiency</h2>\n\n<p>Your <code>is_prime_number()</code> is a very expensive test, and it should not need to exist at all. Rather, the algorithm to factorize the number should just naturally produce only prime factors, never composite factors.</p>\n\n<p>Your <code>sum_prime_factors()</code> is also very inefficient, because it always tries factors up to <code>floor(sqrt(number))</code> — even after <code>number</code> has been reduced by <code>number = number / factor</code>.</p>\n\n<p>Another relatively minor inefficiency is that you should be using integer division (the <code>//</code> operator) rather than floating-point division (the <code>/</code> operator).</p>\n\n<h2>Style</h2>\n\n<p><code>sum_prime_factors()</code> should be broken up, so that it is a generator that yields prime factors. Then, you can call the built-in <code>sum()</code> function on its outputs.</p>\n\n<p><code>print_output()</code> should be named <code>prime_reduction()</code>, and it should return a pair of numbers rather than printing them. It should also be modified to use a loop rather than calling itself recursively, because recursion is slower and risks overflowing the stack.</p>\n\n<p>The main loop (the last statement of the program) is an abuse of list comprehensions — it should be a loop instead. As a matter of style, you shouldn't use a list comprehension if the resulting list is to be discarded. Furthermore, in this case, a \"4\" as input is skipped and does not cause the program to terminate. Rather, the program ends due to the EOF rather than the \"4\".</p>\n\n<h2>Suggested solution</h2>\n\n<pre><code>from itertools import chain, count\nfrom math import floor, sqrt\nimport sys\n\ndef prime_factors(n):\n limit = floor(sqrt(n))\n for f in chain([2], count(3, 2)):\n while n % f == 0:\n yield f\n n //= f\n limit = floor(sqrt(n))\n if f > limit:\n if n > 1:\n yield n\n break\n\ndef prime_reduction(n):\n for i in count(1):\n s = sum(prime_factors(n))\n if s == n:\n return s, i\n n = s\n\nif __name__ == '__main__':\n for n in map(int, sys.stdin):\n if n == 4:\n break\n print(*prime_reduction(n))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T21:13:28.187",
"Id": "409097",
"Score": "0",
"body": "Hello, Thank you for your help. I liked your suggestion, but It fails due to time limit exceeded too"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T00:56:40.473",
"Id": "211509",
"ParentId": "211504",
"Score": "1"
}
},
{
"body": "<p>As others have stated, <code>is_prime_number</code> is a bit inefficient, as well as being called <em>a lot</em>. You might consider caching its result, since it doesn't change. Try something like:</p>\n\n<pre><code>import functools\n\n@functools.lru_cache(maxsize=None)\ndef is_prime_number(number):\n ...\n</code></pre>\n\n<p>And you should see a massive time improvement.</p>\n\n<p>If that's not enough, you're going to have to look into an algorithmic change somewhere. The immediate construct that jumps out at me is that the loop in <code>is_prime_number</code> is very similar to the loop in <code>sum_prime_factors</code>. Figuring out how to combine them is likely to be worth your while.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T02:23:49.143",
"Id": "211590",
"ParentId": "211504",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T23:34:09.857",
"Id": "211504",
"Score": "1",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "Kattis prime reduction challenge"
} | 211504 |
<p>Task : With the page_type and currentpage param I made this code that returns the web script of the web page with active class on the current page through aspx behind code. </p>
<p>Is there a better and a shorter way of code that works just like the code below? (The difference is the else if(page_type == sales) script.append part)</p>
<pre><code>protected string MakeBottomMenu(string page_type)
{
StringBuilder script = new StringBuilder();
string currentPage = System.IO.Path.GetFileName(Request.Url.AbsolutePath);
if (page_type == "office")
{
if(currentPage.Equals("commute_gps.aspx"))
script.Append($"<li class=\"active\"><a href=\"commute_gps.aspx?page_type={page_type}\" class=\"home\"><span class=\"blind\">홈</span></a></li>");
else
script.Append($"<li><a href=\"commute_gps.aspx?page_type={page_type}\" class=\"home\"><span class=\"blind\">홈</span></a></li>");
if (currentPage.Equals("visit_location.aspx"))
script.Append($"<li class=\"active\"><a href=\"visit_location.aspx?page_type={page_type}\" class=\"locate_office\"><span class=\"blind\">방문업체</span></a></li>");
else
script.Append($"<li><a href=\"visit_location.aspx?page_type={page_type}\" class=\"locate_office\"><span class=\"blind\">방문업체</span></a></li>");
if(currentPage.Equals("approval_request.aspx"))
script.Append($"<li class=\"active\"><a href=\"approval_request.aspx?page_type={page_type}\" class=\"request\"><span class=\"blind\">근무기록</span></a></li>");
else
script.Append($"<li><a href=\"approval_request.aspx?page_type={page_type}\" class=\"request\"><span class=\"blind\">근무기록</span></a></li>");
if (currentPage.Equals("address_book.aspx"))
script.Append($"<li class=\"active\"><a href=\"address_book.aspx?page_type={page_type}\" class=\"address\"><span class=\"blind\">주소록</span></a></li>");
else
script.Append($"<li><a href=\"address_book.aspx?page_type={page_type}\" class=\"address\"><span class=\"blind\">주소록</span></a></li>");
}
else if (page_type == "onsite")
{
if (currentPage.Equals("commute_gps.aspx"))
script.Append($"<li class=\"active\"><a href=\"commute_gps.aspx?page_type={page_type}\" class=\"home\"><span class=\"blind\">홈</span></a></li>");
else
script.Append($"<li><a href=\"commute_gps.aspx?page_type={page_type}\" class=\"home\"><span class=\"blind\">홈</span></a></li>");
if (currentPage.Equals("visit_location.aspx"))
script.Append($"<li class=\"active\"><a href=\"visit_location.aspx?page_type={page_type}\" class=\"locate_office\"><span class=\"blind\">방문업체</span></a></li>");
else
script.Append($"<li><a href=\"visit_location.aspx?page_type={page_type}\" class=\"locate_office\"><span class=\"blind\">방문업체</span></a></li>");
if (currentPage.Equals("approval_request.aspx"))
script.Append($"<li class=\"active\"><a href=\"approval_request.aspx?page_type={page_type}\" class=\"request\"><span class=\"blind\">근무기록</span></a></li>");
else
script.Append($"<li><a href=\"approval_request.aspx?page_type={page_type}\" class=\"request\"><span class=\"blind\">근무기록</span></a></li>");
if (currentPage.Equals("address_book.aspx"))
script.Append($"<li class=\"active\"><a href=\"address_book.aspx?page_type={page_type}\" class=\"address\"><span class=\"blind\">주소록</span></a></li>");
else
script.Append($"<li><a href=\"address_book.aspx?page_type={page_type}\" class=\"address\"><span class=\"blind\">주소록</span></a></li>");
}
else if (page_type == "sales")
{
if (currentPage.Equals("sales_calendar.aspx"))
script.Append($"<li class=\"active\"><a href=\"sales_calendar.aspx?page_type={page_type}\" class=\"home\"><span class=\"blind\">홈</span></a></li>");
else
script.Append($"<li><a href=\"sales_calendar.aspx?page_type={page_type}\" class=\"home\"><span class=\"blind\">홈</span></a></li>");
if (currentPage.Equals("visit_location.aspx"))
script.Append($"<li class=\"active\"><a href=\"visit_location.aspx?page_type={page_type}\" class=\"locate_office\" ><span class=\"blind\" > 방문업체</span></a></li>");
else
script.Append($"<li><a href=\"visit_location.aspx?page_type={page_type}\" class=\"locate_office\" ><span class=\"blind\" > 방문업체</span></a></li>");
if (currentPage.Equals("approval_request.aspx"))
script.Append($"<li class=\"active\"><a href=\"approval_request.aspx?page_type={page_type}\" class=\"request\" ><span class=\"blind\" > 근무기록</span></a></li>");
else
script.Append($"<li><a href=\"approval_request.aspx?page_type={page_type}\" class=\"request\" ><span class=\"blind\" > 근무기록</span></a></li>");
if (currentPage.Equals("address_book.aspx"))
script.Append($"<li class=\"active\"><a href=\"address_book.aspx?page_type={page_type}\" class=\"address\" ><span class=\"blind\" > 주소록</span></a></li>");
else
script.Append($"<li><a href=\"address_book.aspx?page_type={page_type}\" class=\"address\" ><span class=\"blind\" > 주소록</span></a></li>");
}
return script.ToString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T00:32:25.977",
"Id": "408985",
"Score": "1",
"body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"."
}
] | [
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Don't use underscores in variable names (<code>page_type</code>).</p></li>\n<li><p>Why do you call this a \"script\"? You're returning a list of <code>LI</code>s, i.e. list items.</p></li>\n<li><p>On a related note: why a <code>StringBuilder</code>? This is a list of strings that at the end gets returned as a single string. So why then not work with a <code>List<string></code> and use <code>string.Join()</code> at the end?</p></li>\n<li><p>If you find yourself copy-pasting things over and over again and changing only parts of what you copy-pasted, you should stop copy-pasting and instead write a method that takes the necessary arguments and returns the required string. All of your list items are the same, except for the LI's class, the link's class, part of the link's URL and the text that is displayed. Imagine you need to change something in that HTML: if this was the return of a method, you'd only need to change it in one place, not dozens.</p></li>\n<li><p>The logic inside <code>page_type == \"office\"</code> and <code>page_type == \"onsite\"</code> seems to be identical. Why then have separate blocks? Again: do not copy-paste code.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T10:25:23.647",
"Id": "211533",
"ParentId": "211506",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T00:17:59.177",
"Id": "211506",
"Score": "0",
"Tags": [
"c#",
"asp.net"
],
"Title": "StringBuilder returing Web script"
} | 211506 |
<p>I'm looking to learn more about data structures, time complexity, and efficient algorithms. I have solved the <a href="https://www.hackerrank.com/challenges/array-left-rotation/problem" rel="nofollow noreferrer">Left Rotation Problem</a>
on HackerRank using JavaScript. I am looking to see ways to optimize the time complexity. I feel like I have a lot to learn, as don't grok Big O.</p>
<pre><code>function main() {
const nd = readLine().split(' ')
const numbers = parseInt(nd[0], 10)
const rotations = parseInt(nd[1], 10)
const arr = readLine().split(' ').map(aTemp => parseInt(aTemp, 10))
const front = arr.slice(0, rotations)
const back = arr.slice(rotations, numbers)
const new_arr = back.concat(front)
console.log(new_arr.join(' '))
}
</code></pre>
<p>I feel like this likely has bad time complexity, as under the hood, I believe the <code>slice</code> function uses a loop and has a time complexity of <span class="math-container">\$O(n)\$</span>. In addition, I'm unsure of how JavaScript implements the merge from the <code>concat</code> method under the hood.</p>
| [] | [
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>Since you are building the array yourself, as opposed to you get a source array from a consumer of your method, I don't think you should create a new array, but rather just adapt the source array. This way, you could avoid <code>slice</code> and <code>concat</code> altogether.</li>\n<li>The number of <code>rotations</code> is an integer. However, reading the description behind the link tells use it's clamped between <code>1</code> <= <code>rotations</code> <= <code>nd</code>. There is a slight optimization here. If <code>rotations</code> = <code>nd</code> you don't have to do anything, since a rotation is circular. An elegant way to check this is to normalize <code>rotations</code> as <code>rotations = rotations % nd;</code> assuming you have already checked <code>rotations</code> againsts the clamped range. if <code>rotations = 0</code>, don't rotate.</li>\n<li>There's another optimization if <code>nd</code> < <code>2</code>, then any rotation is the source itself.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T21:49:33.907",
"Id": "227236",
"ParentId": "211510",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T00:56:54.417",
"Id": "211510",
"Score": "2",
"Tags": [
"javascript",
"performance",
"algorithm",
"programming-challenge",
"array"
],
"Title": "HackerRank - Left Rotation in JavaScript"
} | 211510 |
<p>This is a <code>basic_string</code> implementation that has SSO. It's not done, but the fundamental operations are all there (<code>append</code>, <code>erase</code>, <code>resize</code>, <code>reserve</code>, <code>push_back</code>/<code>pop_back</code>). Proper iterators and my own <code>char_traits</code> impl will be added eventually.</p>
<pre><code>#include <string>
template<typename CharType, typename Traits = std::char_traits<CharType>, typename Allocator = std::allocator<CharType>>
class kbasic_string
{
public:
static const size_t npos = -1;
using iterator = CharType*;
using const_iterator = const CharType*;
friend kbasic_string operator+(const kbasic_string& lhs, const kbasic_string& rhs)
{
return kbasic_string{lhs}.append(rhs);
}
friend kbasic_string operator+(const kbasic_string& lhs, const CharType* rhs)
{
return kbasic_string{lhs}.append(rhs);
}
friend kbasic_string operator+(const kbasic_string& lhs, CharType rhs)
{
return kbasic_string{lhs}.append(rhs);
}
friend std::ostream& operator<<(std::ostream& lhs, const kbasic_string& rhs)
{
lhs.write(rhs.data(), rhs.size());
return lhs;
}
friend std::wostream& operator<<(std::wostream& lhs, const kbasic_string& rhs)
{
lhs.write(rhs.data(), rhs.size());
return lhs;
}
kbasic_string() = default;
kbasic_string(const kbasic_string& other)
{
reserve(other.capacity_);
if (other.size_)
std::copy(other.begin(), other.end() + 1, begin());
size_ = other.size_;
}
kbasic_string(kbasic_string&& other)
{
if (other.on_heap())
{
std::memcpy(&data_, &other.data_, sizeof(CharType*));
std::memset(&other.data_, 0, sizeof(CharType*));
}
else
{
std::copy(other.begin(), other.end() + 1, begin());
}
size_ = other.size_;
capacity_ = other.capacity_;
on_heap_ = other.on_heap_;
other.on_heap_ = false;
}
kbasic_string& operator=(const kbasic_string& other)
{
reserve(other.capacity_);
if (other.size_)
std::copy(other.begin(), other.end() + 1, begin());
size_ = other.size_;
return *this;
}
kbasic_string& operator=(kbasic_string&& other)
{
if (other.on_heap())
{
std::memcpy(&data_, &other.data_, sizeof(CharType*));
std::memset(&other.data_, 0, sizeof(CharType*));
on_heap_ = true;
}
else
{
std::copy(other.begin(), other.end() + 1, begin());
}
size_ = other.size_;
capacity_ = other.capacity_;
other.on_heap_ = false;
return *this;
}
kbasic_string(const CharType* str)
{
size_t size = Traits::length(str);
if (size > capacity_)
reserve(size);
std::copy(str, str + size + 1, data());
size_ = size;
}
kbasic_string& operator=(const CharType* str)
{
size_t size = Traits::length(str);
if (size > capacity_)
reserve(size);
std::copy(str, str + size + 1, data());
size_ = size;
}
void reserve(size_t capacity)
{
if (capacity <= capacity_ || capacity <= 22)
return;
Allocator alloc;
CharType* mem = alloc.allocate(capacity + 1);
if (size_)
std::copy(begin(), end() + 1, mem);
if (on_heap())
alloc.deallocate(data(), capacity_ + 1);
else
on_heap_ = true;
std::memcpy(data_, &mem, sizeof(CharType*));
capacity_ = capacity;
}
void resize(size_t size, CharType app)
{
if (size > size_)
{
reserve(size);
std::fill(end(), end() + (size - size_), app);
*(end() + (size - size_) + 1) = 0;
}
else if (size < size_)
{
erase(end() - (size_ - size), end());
}
else
{
return;
}
size_ = size;
}
void resize(size_t size)
{
resize(size, 0);
}
template<typename Iter, typename = std::enable_if_t<std::_Is_iterator_v<Iter>>>
kbasic_string& erase(Iter first, Iter last)
{
return erase(first - begin(), last - first);
}
kbasic_string& erase(size_t pos, size_t count)
{
if (pos > size_)
throw std::out_of_range("pos is out of range");
std::copy(begin() + pos + count, end() + 1, begin() + pos);
size_ -= count;
return *this;
}
template<typename Iter, typename = std::enable_if_t<std::_Is_iterator_v<Iter>>>
kbasic_string& erase(Iter it)
{
return erase(it - begin(), 1);
}
void pop_back()
{
erase(end() - 1);
}
void clear()
{
erase(begin(), end());
}
kbasic_string& append(const CharType* str, size_t len)
{
if (size_ + len > capacity_)
reserve(size_ + len);
std::copy(str, str + len + 1, begin() + size_);
size_ += len;
return *this;
}
kbasic_string& append(const CharType* str)
{
return append(str, Traits::length(str));
}
kbasic_string& append(const kbasic_string& str)
{
return append(str.data());
}
kbasic_string& append(CharType ch)
{
if (size_ + 1 > capacity_)
reserve(size_ + 1);
iterator prev_end = begin() + size_;
*prev_end = ch;
*(prev_end + 1) = 0;
++size_;
return *this;
}
template<typename Iter, typename = std::enable_if_t<std::_Is_iterator_v<Iter>>>
kbasic_string& append(Iter first, Iter last)
{
if (last - first > capacity_)
reserve(last - first);
std::copy(first, last, begin() + size_);
return *this;
}
void push_back(CharType ch)
{
append(ch);
}
CharType* data() noexcept
{
return on_heap() ? heap_ptr() : data_;
}
const CharType* data() const noexcept
{
return on_heap() ? heap_ptr() : data_;
}
size_t size() const noexcept
{
return size_;
}
size_t length() const noexcept
{
return size_;
}
size_t capacity() const noexcept
{
return capacity_;
}
iterator begin() noexcept
{
return data();
}
const_iterator begin() const noexcept
{
return data();
}
iterator end() noexcept
{
return data() + size_;
}
const_iterator end() const noexcept
{
return data() + size_;
}
bool empty() const noexcept
{
return !size_;
}
CharType& at(size_t n)
{
return data()[n];
}
const CharType& at(size_t n) const
{
return data()[n];
}
CharType& operator[](size_t n)
{
return at(n);
}
const CharType& operator[](size_t n) const
{
return at(n);
}
kbasic_string& operator+=(const kbasic_string& other)
{
return append(other);
}
kbasic_string& operator+=(const CharType* str)
{
return append(str);
}
kbasic_string& operator+=(CharType ch)
{
return append(ch);
}
bool operator==(const kbasic_string& other)
{
return std::equal(begin(), end(), other.begin(), other.end());
}
bool operator==(const CharType* str)
{
return std::equal(begin(), end(), str, str + Traits::length(str));
}
bool operator==(CharType ch)
{
return size_ == 1 && *begin() == ch;
}
bool operator!=(const kbasic_string& other)
{
return !(*this == other);
}
bool operator!=(const CharType* str)
{
return !(*this == str);
}
bool operator!=(CharType ch)
{
return !(*this == ch);
}
~kbasic_string()
{
if (on_heap())
Allocator{}.deallocate(data(), capacity_ + 1);
}
private:
bool on_heap() const
{
return on_heap_;
}
const CharType* heap_ptr() const
{
CharType* ptr = nullptr;
std::memcpy(&ptr, data_, sizeof(CharType*));
return ptr;
}
CharType* heap_ptr()
{
CharType* ptr = nullptr;
std::memcpy(&ptr, data_, sizeof(CharType*));
return ptr;
}
size_t size_ = 0;
size_t capacity_ = 22;
bool on_heap_ = false;
CharType data_[23] = {0};
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:45:44.853",
"Id": "409096",
"Score": "0",
"body": "a small thing: since is c++ it should be std::size_t not size_t"
}
] | [
{
"body": "<p>It's tricky to review something like this where you're imitating an overcomplicated design, so you <em>know</em> certain things are unimplemented (such as iterators), but then other things might also be unimplemented by accident. For example:</p>\n\n<ul>\n<li><p>You take a parameter <code>Traits = std::char_traits<CharType></code> but then you don't use it! The real <code>basic_string</code> would use the traits class for things like where you use <code>std::copy</code>.</p></li>\n<li><p>You take an allocator parameter <code>Allocator = std::allocator<CharType></code> and do use it, kind of, but you don't go through <code>std::allocator_traits<Allocator></code>. Since all you use is <code>a.allocate()</code> and <code>a.deallocate()</code>, this is probably fine in all real-world situations; but really you should be using <code>allocator_traits</code>. It can't hurt.</p></li>\n<li><p>You don't store an <code>Allocator</code> data member of <code>kbasic_string</code>; instead, you default-construct one <em>ex nihilo</em> every time you want to use the allocator. This (plus the previous bullet point, technically) means that your container is not <em>allocator-aware</em>: it won't work with user-defined allocators or allocators such as <code>std::pmr::polymorphic_allocator<char></code>. You get away with it in your tests right now only because <code>std::allocator<char></code> is (A) empty and (B) default-constructible.</p></li>\n<li><p>You do have tests, right?</p></li>\n</ul>\n\n<hr>\n\n<pre><code> std::memcpy(&data_, &other.data_, sizeof(CharType*));\n std::memset(&other.data_, 0, sizeof(CharType*));\n</code></pre>\n\n<p>This is a very strange way of writing</p>\n\n<pre><code> data_ = other.data_;\n other.data_ = nullptr;\n</code></pre>\n\n<p>...oh, I see, your <code>data_</code> is a <code>char[23]</code>, not a <code>char *</code>. Well, okay. I would strongly recommend making it a <code>union</code> of <code>char[23]</code> and <code>char *</code> so that you can copy the pointer member without weird type-punning tricks.</p>\n\n<p>Pedantic nit: Setting all-bits-zero is not technically the same thing as setting to <code>nullptr</code> — the in-memory representation of <code>nullptr</code> need not be all-bits-zero (even though, in practice, it will be).</p>\n\n<p>Also, notice that to be <em>allocator-aware</em> you will have to store a pointer of type <code>std::allocator_traits<Allocator>::pointer</code>, which you <em>definitely</em> cannot assume is all-bits-zero when it's null! For example, <code>boost::interprocess::offset_ptr<char></code> is not all-bits-zero when it's null.</p>\n\n<hr>\n\n<pre><code>bool operator==(const kbasic_string& other)\n</code></pre>\n\n<p>Here and throughout, you forgot the trailing <code>const</code>. These days I recommend making every operator an \"ADL friend\" non-member:</p>\n\n<pre><code>friend bool operator==(const kbasic_string& other, const kbasic_string& other) {\n return std::equal(begin(), end(), other.begin(), other.end());\n}\n</code></pre>\n\n<p>Then it's really obvious if you forget one of the two <code>const</code>s.</p>\n\n<hr>\n\n<pre><code> template<typename Iter, typename = std::enable_if_t<std::_Is_iterator_v<Iter>>>\n kbasic_string& append(Iter first, Iter last)\n {\n if (last - first > capacity_)\n reserve(last - first);\n std::copy(first, last, begin() + size_);\n return *this;\n }\n</code></pre>\n\n<p>Write a test case for this function! For example, <code>string(\"123456789\").append(a, a+3)</code>. There's a bug in the <code>if</code> condition that leads quickly to undefined behavior.</p>\n\n<pre><code>kbasic_string& append(const kbasic_string& str)\n{\n return append(str.data());\n}\n</code></pre>\n\n<p>Also write tests for this function! Since <code>str</code> knows its own <code>size()</code>, does it make sense to throw away that information here? What happens if <code>str</code> contains an embedded <code>'\\0'</code> character — what is <code>string(\"abc\").append(string(\"d\\0e\", 3))</code>?</p>\n\n<hr>\n\n<p>Your use of <code>std::_Is_iterator_v<Iter></code> is sketchy. I would recommend writing your own portable type-trait, something like this:</p>\n\n<pre><code>template<class, class = void> struct is_iterator : std::false_type {};\ntemplate<class T> struct is_iterator<T, decltype(void(std::iterator_traits<T>::iterator_category{}))> : std::true_type {};\n</code></pre>\n\n<p>Orthogonally, you seem to be using <code>_Is_iterator_v</code> almost like pseudocode that magically does whatever you want done. Here you use it to mean \"is an input iterator or better\":</p>\n\n<pre><code>template<typename Iter, typename = std::enable_if_t<std::_Is_iterator_v<Iter>>>\nkbasic_string& append(Iter first, Iter last)\n</code></pre>\n\n<p>Here you use it to mean \"is either <code>kbasic_string::iterator</code> or <code>kbasic_string::const_iterator</code>\":</p>\n\n<pre><code>template<typename Iter, typename = std::enable_if_t<std::_Is_iterator_v<Iter>>>\nkbasic_string& erase(Iter it)\n</code></pre>\n\n<p><code>erase</code> should certainly be rewritten as a non-template:</p>\n\n<pre><code>kbasic_string& erase(const_iterator it)\n</code></pre>\n\n<hr>\n\n<p>Finally, consider whether you could save space by replacing every instance of <code>on_heap_</code> with the condition <code>(capacity_ > 22)</code>. And consider moving the magic number 22 into a variable!</p>\n\n<pre><code>static constexpr size_t SBO_CAPACITY = 22;\nsize_t size_ = 0;\nsize_t capacity_ = SBO_CAPACITY;\nCharType data_[SBO_CAPACITY + 1] = {0};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:03:40.527",
"Id": "211523",
"ParentId": "211515",
"Score": "8"
}
},
{
"body": "<p>I was looking at a method which I considered to be really easy: <code>c_str</code>, however, it doesn't look that easy based on how you implemented it.</p>\n\n<p>Currently, you have a bool indicating whether you should store it on the heap or not. If you replace that by a pointer to the first character. You could implement the <code>onHeap</code> by comparing 2 pointers. Every access to the characters can simply use the pointer, unless for the appending.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:19:12.213",
"Id": "211524",
"ParentId": "211515",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T03:07:44.387",
"Id": "211515",
"Score": "4",
"Tags": [
"c++",
"strings"
],
"Title": "C++ implementation of basic_string"
} | 211515 |
<p>The following code uses a context manager to store and load variables into files.
However, it's very annoying to have to set the <code>value</code> property of what is yielded by the context manager (<code>loaded.value</code>).
I would like to</p>
<ol>
<li>Not have to define a new class like <code>LoadedValue</code></li>
<li>Set the yielded value of the context manager (<code>loaded</code>) to be the value that is saved.</li>
</ol>
<p>Any way of doing either of those two (as well as other helpful improvements) would be greatly appreciated.</p>
<pre><code>import os
import pickle
from contextlib import contextmanager
class LoadedValue:
def __init__(self, value):
self.value = value
def __str__(self):
return "<LoadedValue: {}>".format(self.value)
@contextmanager
def load_manager(load_file="file.pkl"):
with open(load_file, "rb") as f:
loaded_object = LoadedValue(pickle.load(f))
try:
yield loaded_object
finally:
with open(load_file, "wb+") as f:
pickle.dump(loaded_object.value, f)
if __name__ == "__main__":
filename = "test.pkl"
with open(filename, "wb+") as f:
pickle.dump(7, f)
with load_manager(filename) as loaded:
print(loaded) # >>> <LoadedValue: 7>
loaded.value = 5 # this is what I have to do
# loaded = 5 # this is what I want to do
with load_manager(filename) as loaded:
print(loaded) # >>> <LoadedValue: 5>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T03:53:58.040",
"Id": "211517",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Use a context manager to save an object on exit"
} | 211517 |
<p>I have the following function in the database to do string manipulation:</p>
<pre class="lang-sql prettyprint-override"><code>create or replace FUNCTION convert_string
(
input_string IN VARCHAR2
) RETURN VARCHAR2 AS
output_string VARCHAR(8);
BEGIN
IF (input_string IS NULL) THEN
output_string := '';
ELSIF (NOT (SUBSTR(input_string, 6, 1) >= '0' AND SUBSTR(input_string, 6, 1) <= '9')) THEN
output_string := '000' || SUBSTR(input_string, 1, 5);
ELSE
output_string := '00' || input_string;
END IF;
RETURN output_string;
END convert_string;
</code></pre>
<p>I'm using the function to perform checking on 2 tables, so my SQL query will be:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT t1.name
FROM table1 t1
JOIN table2 t2 on t1.id = convert_string(t2.id)
</code></pre>
<p>But let's say I do not want to create a <code>convert_string</code> function in my database, and would like to do everything on the application side. What is the best way to do it?</p>
<p>The function above can be converted to C# code:</p>
<pre class="lang-cs prettyprint-override"><code>public string ConvertString(input)
{
if (String.IsNullOrEmpty(input))
return "";
else if (!(input[5] >= '0' && input[5] <= '9'))
return "000" + input.Substring(0,5);
else
return "00" + input;
}
</code></pre>
<p>Then the SQL query is to be split into 2 database calls:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM table1
</code></pre>
<p>and</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM table2
</code></pre>
<p>Those will be returned to their own data tables, and then do a loop or Linq to join these 2 tables. But I wonder whether there is a more efficient / better way to do this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T09:59:42.613",
"Id": "409021",
"Score": "0",
"body": "But why would you want to join on tables that have incompatible IDs? Wouldn't it be better to \"fix\" the database instead of this hacky solution? Also, don't use `\"\"`, instead use `string.Empty`: the latter expresses that this isn't a string that was erroneously left empty, but an intentionally empty string."
}
] | [
{
"body": "<p>Even if I don't know the actual content, joining tables on client-side is basically a bad idea because you have to load the whole content to the client.</p>\n\n<p>As BCdotWEB mentioned in the comment, the prefered way is to consolidate your data model to avoid such hacks. If that is not possible, your solution with the <code>convert_string</code> should work. If you need a more efficient solution, you could use <a href=\"https://oracle-base.com/articles/8i/function-based-indexes\" rel=\"nofollow noreferrer\">function-based-indexes</a> or <a href=\"https://oracle-base.com/articles/11g/virtual-columns-11gr1\" rel=\"nofollow noreferrer\">virtual columns</a> with indices, which should significantly increase query performance.</p>\n\n<p>One comment to the posted code: The oracle function as well as the c# method do not check the length of the string before accessing the 6'th element which may result in an index out of range exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:37:54.173",
"Id": "211566",
"ParentId": "211519",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T05:50:23.357",
"Id": "211519",
"Score": "2",
"Tags": [
"c#",
"oracle"
],
"Title": "String manipulation over 2 tables in database to application"
} | 211519 |
<p>The problem is as below:</p>
<blockquote>
<p>The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.</p>
<p>Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.</p>
</blockquote>
<pre><code>%%time
import itertools
import time
t1 = time.time()
def prime():
yield 3
yield 7
for i in itertools.count(11, 2):
e = int(i ** .5) + 1
for j in range(2, e + 1):
if i % j == 0:
break
else:
yield i
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
e = int(n ** .5) + 1
for i in range(2, e + 1):
if n % i == 0:
return False
else:
return True
def power_up(n):
# helper function return the next 10 power
i = 1
while 1:
if n < i:
return i
i*=10
def conc(x,y):
# helper function check if xy and yz is prime
if not is_prime((x*power_up(y))+y):
return False
else:
return is_prime(y*power_up(x)+x)
def conc3(x,y,z): # not use, it did not improve the performance
a = conc(x,y)
if not a:
return False
b = conc(x,z)
if not b:
return False
c = conc(y,z)
if not c:
return False
return True
one = []
two = []
three = []
four = []
found = 0
for i in prime():
if found:
break
try:
if i > sum_:
break
except:
pass
one += [i]
for j in one[:-1]: # on the fly list
if conc(i,j):
two += [[i, j]]
for _, k in two: # check against k only if it is in a two pair
if _ == j:
for x in [i, j]:
if not conc(x,k):
break
else:
three += [[i, j, k]]
for _, __, l in three:
if _ == j and __ == k:
for x in [i, j, k]:
if not conc(x,l):
break
else:
four += [[i, j, k, l]]
# print(i, j, k, l)
for _, __, ___, m in four:
if _ == j and __ == k and ___ == l:
for x in [i, j, k, l]:
if not conc(x,m):
break
else:
a = [i, j, k, l, m]
t2 = time.time()
try:
if (
sum(a) < sum_
): # assign sum_ with the first value found
sum_ = sum(a)
except:
sum_ = sum(a)
print(
f"the sum now is {sum(a)}, the sum of [{i}, {j}, {k}, {l}, {m}], found in {t2-t1:.2f}sec"
)
if i > sum_:
# if the first element checked is greater than the found sum, then we are sure we found it,
# this is the only way we can be sure we found it.
# it took 1 and a half min to find the first one, and confirm that after 42min.
# my way is not fast, but what I practised here is to find the number without a guessed boundary
found = 1
print(
f"the final result is {sum_}"
)
</code></pre>
<p>I found the first candidate in 75 sec which I think is to long. I want to see if anyone can give me some suggestion on how to improve the performance.</p>
| [] | [
{
"body": "<p>The obvious answer is to look again at the primality testing. There's no need to test divisibility by every number up to the square root: it suffices to test divisibility by the primes up to the sqrt. Add a cache and you'll probably beat the minute. For something even faster, look at precomputing all the primes in one sieve. If you want to avoid hard-coding the limit of the sieve, try segmenting it: E.g. sieve up to 1000, and if you need more then sieve 1001-2000, using your knowledge of the primes up to sqrt(2000); etc.</p>\n\n<p>Then the actual search looks rather complicated, and I'm not sure it isn't doing more work than necessary. Have you tried just storing the pairs as a dict from larger to set of smaller and checking triples of those which pair with the current prime under consideration?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T06:47:37.540",
"Id": "211522",
"ParentId": "211520",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T06:09:13.463",
"Id": "211520",
"Score": "4",
"Tags": [
"python"
],
"Title": "Project Euler #60 Prime pair sets"
} | 211520 |
<p>For this equation, I need to count possible solutions:</p>
<p><span class="math-container">$$ a + b^2 + c^3 + d^4 \le S $$</span></p>
<p><span class="math-container">$$0\le a,b,c,d \le S$$</span></p>
<p>I tried the following approach:</p>
<pre><code> Integer S=Integer.parseInt(br.readLine());
// get maximum possible value of a,b,c,d which satisfy equation
int a=S;
int b=(int) Math.sqrt(a);
int d=(int) Math.sqrt(b);
int c=(int) Math.cbrt(a);
int count=0;
for (int i = 0; i <= a; i++) {
for (int j = 0; j <= b; j++) {
for (int k = 0; k <= c; k++) {
for (int l = 0; l <= d; l++) {
int total=i+j*j+(int)Math.pow(k, 3)+
(int)Math.pow(l,4);
if(total<=a) {
count++;
}
}
}
}
}
System.out.println(count);
</code></pre>
<p>Time complexity: <span class="math-container">\$O(n \times \sqrt{n} \times \sqrt[3]{n} \times \sqrt[4]{n})\$</span> (Not sure) </p>
<p>For large value, this takes time. Can someone please help me with better solution with time complexity?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:35:30.770",
"Id": "409014",
"Score": "1",
"body": "Are `a,b,c,d` elements of the natural numbers ? Can they be negative, or even complex? Please update the problem statement :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T06:31:39.123",
"Id": "409126",
"Score": "0",
"body": "@RobAu updated problem statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T06:39:24.383",
"Id": "409128",
"Score": "1",
"body": "I have rolled back you last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<blockquote>\n <p>a + b^2 + c^3 + d^4 <= S<br>\n For above equation ,I need to count possible solutions.</p>\n \n <p>I tried following approach.</p>\n\n<pre><code>Integer inp=Integer.parseInt(br.readLine());\n // get maximum possible value of b,c,d which satisfy equation\n int b=(int) Math.sqrt(inp);\n int d=(int) Math.sqrt(b);\n int c=(int) Math.cbrt(inp);\n int count=0;\n</code></pre>\n \n <p>...</p>\n</blockquote>\n\n<p>If I were the interviewer, I would already have marked you down heavily for your choice of variable names. The problem statement defines a, b, c, d, S. The natural choice of variable names for those values are a, b, c, d, S. Using b, c, d for something else almost looks as though you were deliberately trying to make the code unmaintainable.</p>\n\n<hr>\n\n<pre><code> if(total<=inp) {\n count++;\n }\n</code></pre>\n\n<p>Enumerating items one by one is nearly always the wrong way to count something.</p>\n\n<p>If I asked you to count solutions to <span class=\"math-container\">\\$a \\le S\\$</span> would you write a loop? I hope not, because you can do it without any loop or any mathematical operations.</p>\n\n<p>Now, how about <span class=\"math-container\">\\$a + b^2 \\le S\\$</span>? This can be done with one mathematical expression. Hint: start from <span class=\"math-container\">$$\\sum_{b=0}^{\\sqrt{S}} \\textrm{countA}(S - b^2)$$</span></p>\n\n<p>Cubes already grow quite fast, so</p>\n\n<pre><code>for (int c = 0; c <= maxC; c++) {\n for (int d = 0; d <= maxD; d++) {\n count += countAB(S - c*c*c - d*d*d*d)\n }\n}\n</code></pre>\n\n<p>would be reasonably efficient. If you really want to microoptimise you can eliminate the multiplications in favour of some accumulators and addition, but that's probably not necessary for an interview question. They might ask about it in a follow-up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T06:38:39.070",
"Id": "409127",
"Score": "0",
"body": "Thanks @Peter . Corrected variable names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T06:52:19.290",
"Id": "409129",
"Score": "0",
"body": "What I understood is using all combination of a,b we can get possible count of solution for a,b variable & for c,d loop can be used. Both count can be multiplied. `Solutions for a<=S = S+1 `, ` Solution for b <= \\sqrt (S-a) ` So for ex S=2 , we have countAB= (S+1) \\times \\sqrt(S-a)= 3*2 =6 but here solution (a,b) (2,1) is included which do not satisfy equation. Or did I got it wrong ? Also can you please briefly explain why following code is wrong to count something ? ` if(total<=S) {\n count++;\n }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:43:31.637",
"Id": "409151",
"Score": "0",
"body": "Hopefully the edit makes it clearer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:32:03.550",
"Id": "211527",
"ParentId": "211526",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T08:04:14.520",
"Id": "211526",
"Score": "1",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Solving a multi variable polynomial"
} | 211526 |
<p>I have simple class with the public <code>build</code> method I want to test. Currently I assert all values it returns in every test. Is it a good practice or I should write one test for static values and in other tests only check values which change depending on input?</p>
<p><strong>Implementation</strong></p>
<pre><code>class FiltersAttachment:
TYPE_OPTIONS = [
{"text": "All types", "value": "all"},
{"text": ":link: Webpages", "value": "web_pages"}
]
STATUS_OPTIONS = [
{"text": "Available / Unavailable", "value": "all"},
{"text": ":white_circle: Available", "value": "available"},
{"text": ":red_circle: Unavailable", "value": "unavailable"}
]
@classmethod
def _filter_options(cls, options, selected):
return list(filter(lambda t: t['value'] == selected, options))
@classmethod
def build(cls, check_type='', status=''):
return {
'fallback': 'Filters',
'callback_id': 'resource_filters',
'color': '#d2dde1',
'mrkdwn_in': ['text'],
'actions': [
{
'name': 'resource_type',
'text': 'Type',
'type': 'select',
'options': cls.TYPE_OPTIONS,
'selected_options': cls._filter_options(
cls.TYPE_OPTIONS, check_type)
},
{
'name': 'resource_status',
'text': 'Status',
'type': 'select',
'options': cls.STATUS_OPTIONS,
'selected_options': cls._filter_options(
cls.STATUS_OPTIONS, status)
}
]
}
</code></pre>
<p><strong>Tests</strong></p>
<pre><code>class TestFiltersAttachment(TestCase):
def assert_attachment(self, attachment):
self.assertEqual(attachment['fallback'], 'Filters')
self.assertEqual(attachment['callback_id'], 'resource_filters')
self.assertEqual(attachment['color'], '#d2dde1')
self.assertEqual(attachment['mrkdwn_in'], ['text'])
type_action = attachment['actions'][0]
self.assertEqual(type_action['name'], 'resource_type')
self.assertEqual(type_action['text'], 'Type')
self.assertEqual(type_action['type'], 'select')
self.assertEqual(type_action['options'][0]['text'], 'All types')
self.assertEqual(type_action['options'][0]['value'], 'all')
self.assertEqual(type_action['options'][1]['text'], ':link: Webpages')
self.assertEqual(type_action['options'][1]['value'], 'web_pages')
status_action = attachment['actions'][1]
self.assertEqual(status_action['name'], 'resource_status')
self.assertEqual(status_action['text'], 'Status')
self.assertEqual(status_action['type'], 'select')
self.assertEqual(status_action['options'][0]['text'], 'Available / Unavailable')
self.assertEqual(status_action['options'][0]['value'], 'all')
self.assertEqual(status_action['options'][1]['text'], ':white_circle: Available')
self.assertEqual(status_action['options'][1]['value'], 'available')
self.assertEqual(status_action['options'][2]['text'], ':red_circle: Unavailable')
self.assertEqual(status_action['options'][2]['value'], 'unavailable')
def test_all_type_selected(self):
attachment = FiltersAttachment.build(check_type='all')
self.assert_attachment(attachment)
selected_type = attachment['actions'][0]['selected_options'][0]
self.assertEqual(selected_type['text'], 'All types')
self.assertEqual(selected_type['value'], 'all')
def test_all_status_selected(self):
attachment = FiltersAttachment.build(status='all')
self.assert_attachment(attachment)
selected_status = attachment['actions'][1]['selected_options'][0]
self.assertEqual(selected_status['text'], 'Available / Unavailable')
self.assertEqual(selected_status['value'], 'all')
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T09:52:09.737",
"Id": "211532",
"Score": "1",
"Tags": [
"python",
"unit-testing"
],
"Title": "Testing class which returns big dictionary"
} | 211532 |
<p>So, I wanted to have the count for number of pairs of same integer there are in an array for which I used a HashMap</p>
<p>Input contains two lines:</p>
<blockquote>
<ol>
<li><p>Integer n:</p>
<p>Signifies the size of input</p></li>
<li><p>Input numbers separated by white space character:<br>
E.g 4 6 6 7 7 8 7 6 4</p></li>
</ol>
</blockquote>
<p>For the same input,</p>
<blockquote>
<p>Expected Output:</p>
<p>3</p>
</blockquote>
<pre><code>import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class SockMerchant {
public int[] returnsockArr() {
Scanner sc = new Scanner(System.in);
int arraySize = sc.nextInt();
int[] sockArr = new int[arraySize];
for(int i = 0;i <= arraySize-1; i++) {
sockArr[i] = sc.nextInt();
}
sc.close();
return sockArr;
}
public int returnCount(Map<String, Object> mapCount) {
int count = 0;
for(String keyName : mapCount.keySet()) {
int value = (int)mapCount.get(keyName);
count = count+(value/2);
}
return count;
}
public int setMapAndReturnCount(int[] sockArr) {
Map<String, Object> mapCount = new HashMap<String, Object>();
for(int j = 0;j<= sockArr.length-1;j++) {
if(mapCount.containsKey(Integer.toString(sockArr[j]))) {
mapCount.put(Integer.toString(sockArr[j]), (int)mapCount.get(Integer.toString(sockArr[j]))+1);
}
else {
mapCount.put(Integer.toString(sockArr[j]), 1);
}
}
return returnCount(mapCount);
}
public static void main(String args[]) {
SockMerchant sm = new SockMerchant();
int[] sockArr = sm.returnsockArr();
int finalCount = sm.setMapAndReturnCount(sockArr);
System.out.println(finalCount);
}
}
</code></pre>
<p>I think that I have complicated the solution a bit too much</p>
<p>Is there a better approach to do the same thing?</p>
| [] | [
{
"body": "<p>There are couple of improvement possible in your code.</p>\n\n<p>In this method <code>setMapAndReturnCount</code> you should change the declaration of map from,</p>\n\n<pre><code>Map<String, Object> mapCount = new HashMap<String, Object>();\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Map<Integer, Integer> mapCount = new HashMap<Integer, Integer>();\n</code></pre>\n\n<p>As you know, you want to store the input array numbers as key in Map and value is the count of occurence of a particular number in the array.</p>\n\n<p>By using <code>Object</code> class as value in Map, you are defeating one of the main purpose of having generics implementation in Java. If you use <code>Object</code> then you need to uselessly cast, and otherwise don't have to.</p>\n\n<p>Another point in same method, you can write your for loop in a better way like this, instead of your current code which does double work of first checking through <code>containsKey</code> and then uses <code>mapCount.get</code> to again pick the value of key.</p>\n\n<pre><code>public int setMapAndReturnCount(int[] sockArr) {\n Map<Integer, Integer> mapCount = new HashMap<Integer, Integer>();\n for (int j = 0; j < sockArr.length; j++) {\n Integer count = mapCount.get(sockArr[j]);\n if (count == null) {\n mapCount.put(sockArr[j], 1);\n } else {\n mapCount.put(sockArr[j], count + 1);\n }\n }\n return returnCount(mapCount);\n}\n</code></pre>\n\n<p>Similarly, you can change <code>returnCount</code> method to this,</p>\n\n<pre><code>public int returnCount(Map<Integer, Integer> mapCount) {\n int count = 0;\n for (Integer value : mapCount.values()) {\n count += (value / 2);\n }\n return count;\n}\n</code></pre>\n\n<p>As you don't need to first iterate on keySet and then retrieve the values with <code>get</code> which will be slower, and instead just iterate it on values as that is what you need for calculating number of pairs, which will be relatively faster.</p>\n\n<p>Also, if you are using Java-8 and above,</p>\n\n<p>You can change your <code>returnCount</code> to one liner like this,</p>\n\n<pre><code>public int returnCount(Map<Integer, Integer> mapCount) {\n return mapCount.values().stream().mapToInt(x -> x / 2).sum();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T13:10:10.060",
"Id": "211543",
"ParentId": "211537",
"Score": "3"
}
},
{
"body": "<p>I have tried to simplify your code like this.</p>\n\n<pre><code>import java.util.HashSet;\nimport java.util.Scanner;\nimport java.util.Set;\n\npublic class SockMerchant {\n\n private int[] returnSockArr() {\n Scanner sc = new Scanner(System.in);\n int arraySize = sc.nextInt();\n int[] sockArr = new int[arraySize];\n for(int i = 0;i <= arraySize-1; i++) {\n sockArr[i] = sc.nextInt();\n }\n sc.close();\n return sockArr;\n }\n\n private int returnCount(int[] sockArr) {\n int count = 0;\n Set<Integer> uniqueElements = new HashSet<>();\n for (int i: sockArr) {\n if(uniqueElements.contains(i)) {\n count ++;\n uniqueElements.remove(i);\n } else {\n uniqueElements.add(i);\n }\n }\n return count;\n }\n\n public static void main(String args[]) {\n SockMerchant sm = new SockMerchant();\n int[] sockArr = sm.returnsockArr();\n int finalCount = sm.returnCount(sockArr);\n System.out.println(finalCount);\n }\n}\n</code></pre>\n\n<p>I have used your <code>returnSockArr</code> as it is for reading the numbers. Then I have removed <code>setMapAndReturnCount</code> method which uses <code>Map</code> for storing numbers. Instead I am calling <code>returnCount</code> and calculate the number of pairs. </p>\n\n<p>In that method I am putting the number in to a <code>Set</code> if the number is not present in the 'Set'. If number is present the <code>count</code> is incremented and that number is removed from the <code>Set</code>. So <code>count</code> won't be incremented when a number is seen odd times in the list. </p>\n\n<p>And am sure it can be again simplified :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T14:06:57.330",
"Id": "413982",
"Score": "1",
"body": "Welcome to code review! You’ve presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works & why it is better than the original) so that the author & other readers can learn from your thought process. From the help page [_How do I write a good answer?_](https://codereview.stackexchange.com/help/how-to-answer):: \"_Every answer must make at least one **insightful observation** about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review_\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:54:03.660",
"Id": "214034",
"ParentId": "211537",
"Score": "-1"
}
},
{
"body": "<p>Separate input handling from the algorithm. E.g. move reading the input from <code>returnsockArr</code> to the main method and change the method to accept an array (of Integers or Strings, the algorithm doesn't really care as long as it receives Comparables). Then you can create test cases by just passing different arrays. Adding the burden of handling input to your algorithm makes it less reusable.</p>\n\n<p>As for the algorithm, sorting the array and processing it once, keeping count of adjacent objects that are equal, would be lot simpler and less error prone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T14:06:30.223",
"Id": "214039",
"ParentId": "211537",
"Score": "0"
}
},
{
"body": "<p>Naming matters.</p>\n\n<pre><code>int[] sockSizes = {4, 6, 6, 7, 7, 8, 7, 6, 4};\nint count = Socks.countPairs(sockSizes);\n\n/**\n * Determine the number of sock pairs one can form.\n * @param sockSizes of single socks available.\n * @return the number of pairs that can be formed.\n */\npublic static int countPairs(int[] sockSizes) {\n Map<Integer, Integer> sockSizeCounts = new HashMap<>();\n for (int sockSize : sockSizes) {\n sockSizeCounts.merge(sockSize, 1, Integer::sum);\n }\n return sockSizeCounts.values().stream()\n .mapToInt(c -> c / 2)\n .sum();\n}\n</code></pre>\n\n<ul>\n<li>The problem needs a bit of explanation; javadoc might help; that 4 5 4 6 4 is 1 pair of 4.</li>\n<li>Diamond operator <code><></code> saves a bit.</li>\n<li>For-each loop to take elements without the need to introduce an index/iterator.</li>\n<li>Walking over the <code>Map.keySet()</code> and calling <code>get(key)</code>, should be done as walking over the <code>Map.entrySet()</code> with <code>getKey()</code> and <code>getValue()</code>.</li>\n<li><a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Map.html#merge(K,V,java.util.function.BiFunction)\" rel=\"nofollow noreferrer\"><code>Map.merge</code></a> does exactly a frequency count; which needs a bit of explanation; read the javadoc.</li>\n<li>Summing the integer half of all values can be done elegantly by a stream expression; your code is however good style too.</li>\n</ul>\n\n<p>Overall, just a manco on progressive Java constructs.</p>\n\n<p>By the way, a fixed sized array of socks is probably inappropriate in this problem area. <code>List<Integer> socksDrawer = new ArrayList<>();</code> <strong>;)</strong></p>\n\n<hr>\n\n<p><strong>I just saw that the question is from 2015. <em>No wonder!</em></strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T14:12:58.607",
"Id": "214040",
"ParentId": "211537",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T11:49:16.917",
"Id": "211537",
"Score": "0",
"Tags": [
"java",
"beginner",
"array"
],
"Title": "Counting number of pairs in an integer array"
} | 211537 |
<p>I tried solving the problem in the following manner; I am just a beginner and wanted to know my mistakes and a more efficient way with better time complexity (if any).</p>
<pre><code> public class d3 {
public static void main(String[] args){
String Search="loop";
String[] letters = Search.split("") ;
int counter;
String[] words={"pole","pool","lopo","book","kobo"};
for(int i=0;i<words.length;i++)
{
counter=0;
String ssplit[] = words[i].split("");
for(int j=0;j<words[i].length();j++)
{
if(letters.length==ssplit.length)
{
for(int k=0;k<letters.length;k++)
{
if(letters[j].equals(ssplit[k]))
{counter++;
ssplit[k]="*";
break;
}
}
if (counter == 4)
{
System.out.println(words[i]);
}
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T13:00:20.900",
"Id": "409034",
"Score": "0",
"body": "Hi Aditya. Do you have to use arrays for the words and characters or can you use another structure ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:52:35.950",
"Id": "409065",
"Score": "0",
"body": "@gervais.b I'm currently not too familiar with other data structures. But I'm open to suggestions. Is there a better option than using arrays?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:53:39.847",
"Id": "409066",
"Score": "0",
"body": "@PeterTaylor Thank you for pointing out the bug. I'll try to fix it and update the question as soon as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:23:33.123",
"Id": "409089",
"Score": "0",
"body": "Just for inspiration, here's something to consider, without going into the depth of a full answer. If I understand correctly, your goal is to return all the words from your dictionary that contain the same length and character set as your input word. One approach might be to take your dictionary and for every word sort the characters in alphabetical order. Then generate a one-to-many map of the sorted versions of the words to all the words they can make up. Then, once you possess such a map, perform the same operation on the input word, and you're returning a simple key/value lookup; O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:29:21.047",
"Id": "409091",
"Score": "0",
"body": "The advantage to such an approach would be that it can process your dictionary offline, offloading the work of testing for your condition and effectively creating a hash index for your search criteria. While generating such a map might take a while, it would only need to be done when the dictionary is modified, while making your performance of searching for these words extremely good, since you can instantly skip to your answer without ever processing any irrelevant words. This approach would make sense if you have a dictionary that stays the same for many inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:02:27.137",
"Id": "409094",
"Score": "0",
"body": "@NateGardner you should have made an answer from your good suggestion ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:19:13.637",
"Id": "409146",
"Score": "0",
"body": "@NateGardner Can you please explain what you mean by \"one-to-many map of the sorted versions of the words\". Why do I need to do that? Once I arrange the characters of all the words in the dictionary alphabetically, I could do the same with the input word and then simply compare it with the entries in the dictionary one by one without getting into comparing each character individually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T22:39:35.707",
"Id": "409276",
"Score": "0",
"body": "@Aditya, an example of an entry in the one-to-many map would look like this: `\"elop\": [\"lope\", \"pole\"]`. Thus every word in your dictionary would enter this map. let's say the user enters the word \"pole.\" I understand the goal of your program is to return a list of words from your dictionary of the same length that use exactly the same letters, but in any order. Thus all you need to do in order to complete this operation, after having created a one-to-many map, is to sort the letters in the word \"pole\" to \"elop\", then access the `elop` key in your map, and return the associated values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T23:18:55.773",
"Id": "409280",
"Score": "0",
"body": "There are essentially two operations your code must complete:\n\n1. Reduce the dictionary set to words of the same length.\n2. Further reduce the dictionary set to words that have the same character frequency.\n\nBecause maps directly access the information you want if you know its associated key, both of these steps can be reduced to O(1), leaving the only complex work sorting the input string's characters to its equivalent key, which is O(n) where n is the length of the input string. For input strings with fewer characters than your dictionary has words, this is the most efficient solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:44:22.557",
"Id": "409359",
"Score": "1",
"body": "@NateGardner I'll definitely look into and try the alternative solution you provided. Thank you"
}
] | [
{
"body": "<p>welcome on Codereview.</p>\n\n<p>I am pretty sure that you will find many other ways to do it the comments from @NateGardner is already a good suggestion. But the goal is to review your code so I will just try to suggest some improvements to your code.</p>\n\n<p>First of all I will just reformat the code, create a dedicated class for it and define the input and output.</p>\n\n<pre><code>class WordFinder {\n private final String[] words;\n WordFinder(String[] words) {\n this.words = new String[words.length];\n System.arraycopy(words, 0, this.words, 0, words.length);\n }\n String[] find(String word) {\n // Your code here\n }\n}\n</code></pre>\n\n<p>Then you can start to split your nested logic in different methods and use exiting methods to simplify your code (like <code>String#toCharArray()</code> instead of <code>String#split(\"\")</code>)</p>\n\n<pre><code> String[] find(String word) {\n String[] result = new String[this.words.length];\n char[] letters = word.toCharArray();\n int counter = 0;\n for (String candidate : this.words) {\n if ( this.matches(letters, candidate.toCharArray()) ) {\n result[counter++] = candidate;\n }\n }\n return Arrays.copyOf(result, counter);\n }\n</code></pre>\n\n<p>As said in the beginning, there is a lot of way to test two words for matching and I am sure that you will find the best one. For this answer, I decided to compare the hash of each array of <code>char</code>.</p>\n\n<hr>\n\n<p>Here is my code if you want. But if you can use other structure from the collections or the stream API, this one can be totally different.</p>\n\n<pre><code>public class WordFinder {\n\n private final String[] words;\n\n public WordFinder(String[] words) {\n this.words = new String[words.length];\n System.arraycopy(words, 0, this.words, 0, words.length);\n }\n\n public String[] find(String word) {\n String[] result = new String[this.words.length];\n char[] letters = word.toCharArray();\n int counter = 0;\n for (String candidate : this.words) {\n if ( matches(letters, candidate.toCharArray()) ) {\n result[counter++] = candidate;\n }\n }\n return Arrays.copyOf(result, counter);\n }\n\n private boolean matches(char[] requirement, char[] candidate) {\n /* Edited to replace Arrays.hashCode with Arrays.equals, see comments\n return candidate.length==requirement.length &&\n hash(candidate)==hash(requirement);*/\n\n if ( candidate.length!=requirement.length ) {\n return false;\n } \n char left = Arrays.copyOf(requirement, requirement.length);\n Arrays.sort(left);\n char right = Arrays.copyOf(candidate, candidate.length);\n Arrays.sort(right );\n return Arrays.equals(left, right);\n }\n\n /*private int hash(char[] array) {\n char[] copy = Arrays.copyOf(array, array.length);\n Arrays.sort(copy);\n return Arrays.hashCode(copy);\n }*/\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:53:18.403",
"Id": "409114",
"Score": "0",
"body": "The most significant suggestion of this answer introduces a bug. Comparing hashes is a valid way of showing that two objects are different, but it is not a valid way of showing that they're the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:01:07.200",
"Id": "409132",
"Score": "0",
"body": "\"For any two char arrays a and b such that `Arrays.equals(a, b)`, it is also the case that `Arrays.hashCode(a) == Arrays.hashCode(b)`.\" https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#hashCode(char[])\n\nBut if you prefer you can use `Arrays.equals` once they are sorted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:37:36.777",
"Id": "409149",
"Score": "0",
"body": "You are arguing my point. It doesn't say \"*For any two char arrays a and b such that Arrays.hashCode(a) == Arrays.hashCode(b), it is also the case that Arrays.equals(a, b)*\". And that can't be the case, if for no other reason then due to the pigeon-hole principle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T10:36:02.203",
"Id": "409175",
"Score": "0",
"body": "@PeterTaylor it may be due to the language that is not my native one. But I don't get the nuance. I will edit my code to replace the hash with `Arrays.equals`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T10:51:51.277",
"Id": "409179",
"Score": "0",
"body": "Perhaps mathematical notation translates better than natural language. \\$A \\implies B\\$ is not the same as \\$B \\implies A\\$. Knowing that \\$A \\implies B\\$ and \\$B\\$ does not tell you anything about \\$A\\$. Here \\$A\\$ is `Arrays.equals(a, b)` and \\$B\\$ is `Arrays.hashCode(a) == Arrays.hashCode(b)`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T21:16:54.983",
"Id": "211578",
"ParentId": "211538",
"Score": "0"
}
},
{
"body": "<p>Whitespace is very important for readability. For posting to Stack Exchange sites I recommend replacing tabs with spaces, because otherwise the site does that for you and the tabstops might not match. Here, though, the whitespace is so crazy that I think you need to look at configuring your IDE to pretty-print the code. Reformatting so that I can understand the structure:</p>\n\n<blockquote>\n<pre><code>public class d3 {\n public static void main(String[] args){\n String Search=\"loop\";\n String[] letters = Search.split(\"\") ;\n int counter;\n\n String[] words={\"pole\",\"pool\",\"lopo\",\"book\",\"kobo\"};\n\n for(int i=0;i<words.length;i++)\n {\n counter=0;\n String ssplit[] = words[i].split(\"\");\n for(int j=0;j<words[i].length();j++)\n {\n if(letters.length==ssplit.length)\n {\n for(int k=0;k<letters.length;k++)\n {\n if(letters[j].equals(ssplit[k]))\n {\n counter++;\n ssplit[k]=\"*\";\n break;\n }\n }\n if (counter == 4)\n {\n System.out.println(words[i]);\n }\n }\n }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h3>Names</h3>\n\n<p>Java convention is that camel-case names which start with a capital letter are types (classes, interfaces, etc), so <code>Search</code> as the name of a variable is unexpected.</p>\n\n<p><code>counter</code> is not entirely uninformative, but a better name would tell me <em>what</em> it counts. Similarly, it would be helpful to distinguish which variables relate to the search query and which to the items searched. The best convention I've seen there is PHP's <code>needle</code> and <code>haystack</code>, so I would suggest <code>needleLetters</code> and <code>haystackWords</code>.</p>\n\n<hr>\n\n<h3>foreach statement</h3>\n\n<p>Instead of <code>for(int i=0;i<words.length;i++) ... words[i]</code> you can use <code>for (String word : words) ... word</code>. This removes a variable and simplifies the naming, making it easier to see what the code does.</p>\n\n<hr>\n\n<h3>Decomposing strings</h3>\n\n<p><code>String</code> has a method <code>toCharArray()</code>. I think it would make more sense to use that than <code>split(\"\")</code>.</p>\n\n<hr>\n\n<h3>Don't put something in a loop which can go outside it</h3>\n\n<blockquote>\n<pre><code> for(int j=0;j<words[i].length();j++)\n {\n if(letters.length==ssplit.length)\n {\n ...\n }\n }\n</code></pre>\n</blockquote>\n\n<p>could be rewritten</p>\n\n<pre><code> if(letters.length==ssplit.length)\n {\n for(int j=0;j<ssplit.length;j++)\n {\n ...\n }\n }\n</code></pre>\n\n<p>Executing the test once is more efficient, and it's also easier to understand because the maintainer doesn't have to reason about loop invariants to work out what might have changed the second time the test is executed.</p>\n\n<p>Since there's nothing after this test in the loop body, an alternative would be</p>\n\n<pre><code> if(letters.length!=ssplit.length)\n {\n continue;\n }\n\n for(int j=0;j<ssplit.length;j++)\n {\n ...\n }\n</code></pre>\n\n<hr>\n\n<h3>Beware hard-coded constants</h3>\n\n<p>Why</p>\n\n<pre><code> if (counter == 4)\n {\n System.out.println(words[i]);\n }\n</code></pre>\n\n<p>? That's a bug. The comparison should be with <code>letters.length</code>. Also, it would make more sense to move the test outside the loop over <code>j</code>.</p>\n\n<hr>\n\n<h3>Use advanced data structures</h3>\n\n<blockquote>\n<pre><code> for(int j=0;j<words[i].length();j++)\n {\n for(int k=0;k<letters.length;k++)\n {\n if(letters[j].equals(ssplit[k]))\n {\n counter++;\n ssplit[k]=\"*\";\n break;\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>takes time proportional to <code>words[i].length() * letters.length</code>. If you use <code>java.util.HashMap<Character, Integer></code> to store a per-character count, you can generate a representation for each word in time proportional to the length of the word, and you can compare the representations of two words in time proportional to the length of each word. In this toy example it doesn't matter, but for real applications the difference between <span class=\"math-container\">\\$O(n^2)\\$</span> and <span class=\"math-container\">\\$O(n)\\$</span> can be the difference between a project being feasible and not. The first place to look for optimisations is always the algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:01:07.967",
"Id": "409155",
"Score": "0",
"body": "Thank you for responding. I had no clue that indentation could be so important. And I'll make sure I use better variable names. You mentioned a bug in the \" if \" statement. I understand that if the length of the search word and the words in the dictionary are greater than 4 than the results produced will not be accurate. But since I know the word-length and as long as it is not something the user will input, it is okay to use constants right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T10:36:26.500",
"Id": "409176",
"Score": "0",
"body": "One of the axes of code quality is brittleness. If changing the search word means that you have to make changes elsewhere, the code is brittle. The problem is that in six months you might have forgotten about the changes which you need to make elsewhere. Making the code less brittle now costs very little, and potentially saves a lot of debugging in the future."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:51:49.883",
"Id": "211587",
"ParentId": "211538",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211587",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T11:53:48.380",
"Id": "211538",
"Score": "2",
"Tags": [
"java"
],
"Title": "Given a word, find other words in an array with same length and same characters"
} | 211538 |
<p>Here's my Queue implementation in ES6,</p>
<pre><code>class Queue{
constructor(){
this.head = null;
this.tail = null;
}
offer(item){
const p = new Node(item);
if(!this.head){
this.head = p;
this.tail = p;
return;
}
this.tail.next = p;
this.tail = p;
}
poll(){
const item = this.head;
this.head = this.head.next;
return item;
}
peek(){
return this.head.val;
}
isEmpty(){
return this.head === null;
}
}
</code></pre>
<p>Please review on all fronts.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:28:23.903",
"Id": "409053",
"Score": "0",
"body": "Why is `p` assigned to both `this.head` and `this.tail`? What is the expected result?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T17:05:45.407",
"Id": "409070",
"Score": "0",
"body": "If that's the first node it's both the head and tail. The next node onwards offer moves the tail and poll moves the head. If I had one node and didn't assign both head and tail to it, the offer wouldn't work on the second node, since there's no tail defined yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-22T23:07:59.473",
"Id": "409981",
"Score": "4",
"body": "Did you have a class definition for `Node`? If so, please [edit] your post to include it... otherwise this code appears broken, revealing an error after instantiating a Queue object and calling the `offer` method: `Uncaught TypeError: Illegal constructor`"
}
] | [
{
"body": "<h2>Does not work, can be mutated</h2>\n\n<p>You did not even test this object. Please take time to make sure the code you put up for review is at least working next time. :)</p>\n\n<h3>Bugs.</h3>\n\n<p>You don't tests if <code>head</code> is defined for the functions <code>peek</code>, and <code>poll</code>.</p>\n\n<pre><code>const q = new Queue();\nq.peek(); // throws TypeError cannot read property val of null\nq.poll(); // throws TypeError cannot read property next of null\n</code></pre>\n\n<p>Can only Get one object from the <code>Queue</code> per group of <code>offer</code> calls</p>\n\n<pre><code>q.offer(\"A\");\nq.offer(\"B\");\nq.poll(); // return \"A\"\nq.peek(); // throws TypeError cannot read property val of null\nq.poll(); // throws TypeError cannot read property next of null\n\n\n// OR\nq.offer(\"A\");\nq.offer(\"B\");\nq.poll(); // return \"A\"\nq.offer(\"C\");\nq.poll(); // return \"C\" What happened to \"B\"\n</code></pre>\n\n<h3>Mutation</h3>\n\n<p>You have not encapsulated the object state and thus can be mutated in many ways to produce unexpected behaviours</p>\n\n<pre><code>const q = new Queue()\nq.offer(\"foo\");\nq.head.tail = q.head; \nwhile(!q.isEmpty()) { console.log(q.poll().val) } // never stops\n\n// and\nq.head = undefined;\nq.isEmpty(); // incorrectly returns false\n</code></pre>\n\n<h2>Bloated</h2>\n\n<p>The property <code>Queue.tail</code> does nothing and is just noise. </p>\n\n<p>I am guessing you wanted to use it to make <code>offer</code> quicker without needing to step all the way down the links from <code>head</code> but that will require a doubly linked list. </p>\n\n<p>You could just use an array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T06:51:39.240",
"Id": "211597",
"ParentId": "211545",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T13:38:01.827",
"Id": "211545",
"Score": "1",
"Tags": [
"javascript",
"queue"
],
"Title": "Queue implementation in ES6"
} | 211545 |
<h3>Synopsis:</h3>
<p>I wanted something for macOS (and Linux; maybe eventually Windows) that would simply wait for the user to connect a storage device and automatically select, or otherwise output the information to be used, read, manipulated, etc.</p>
<p>In its current form, it just prints to the shell, but you could assign the output to a list or variable for read/write operations and so on. It will respond to any new entries in the <code>/dev</code> system directory, including most USB devices, SD Cards, Webcams, and so on. You can test it by running the script in one window, and running something like <code>sudo touch /dev/{x,y,z}</code> in another.</p>
<p>I plan to use it to help people (those of us who are less technically inclined) migrate to Linux by automating the creation of bootable flash drives, but you can do what you like with it.</p>
<p>Open-ended feedback and suggestions are welcome. Please try to post example code pertaining to your suggestions, and don't be afraid to say something positive.</p>
<h3>Usage:</h3>
<pre><code><b>user@macOS:~$</b> ./devlisten.py
/dev/disk2
/dev/rdisk2
/dev/disk2s1
/dev/rdisk2s1
</code></pre>
<h3>Code:</h3>
<pre><code>#!/usr/bin/env python3
import os
import re
import time
import difflib
try:
os.mkdir('/tmp/dev')
except FileExistsError:
pass
except FileNotFoundError:
print('No /tmp directory found.')
exit()
except OSError:
print('Read-only file system.')
exit()
file1 = open('/tmp/dev/1', 'w')
for x in os.listdir('/dev'):
file1.write(x + '\n')
file1.close()
try:
diff = False
while diff == False:
time.sleep(0.25)
file2 = open('/tmp/dev/2', 'w')
for x in os.listdir('/dev'):
file2.write(x + '\n')
file2.close()
text1 = open('/tmp/dev/1').readlines()
text2 = open('/tmp/dev/2').readlines()
for line in difflib.unified_diff(text1, text2):
for line in re.finditer(r'(?<=^\+)\w.*$', line, re.MULTILINE):
print('/dev/' + line.group(0))
diff = True
except KeyboardInterrupt:
print()
exit()
</code></pre>
| [] | [
{
"body": "<p>Prefer to use <code>$TMPDIR</code> if set, and <code>/tmp</code> only as a fallback. That's the standard practice that allows users to have separate, private temporary directories, for example, so don't subvert it! You probably ought to consider <code>tempfile.TemporaryDirectory()</code> as an alternative.</p>\n\n<p>Error messages should go to standard error channel, not standard output.</p>\n\n<p>I don't know Mac OS, but on Linux I'd expect you to wait on <code>inotify</code>, rather than polling the <code>dev</code> directory. There's a choice of Python interface to <code>inotify</code>, but I'm not in a position to recommend any in particular.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:17:21.023",
"Id": "409078",
"Score": "2",
"body": "macOS has FSEvents (https://en.wikipedia.org/wiki/FSEvents). I don't know much about it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T14:08:27.650",
"Id": "211548",
"ParentId": "211546",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>context managers</p>\n\n<p>You should really open and close files with the <code>with</code> statement <a href=\"https://www.python.org/dev/peps/pep-0343/\" rel=\"noreferrer\">see PEP343</a></p></li>\n<li><p><code>if __name__ == '__main__':</code> guard</p>\n\n<p>Python idiom is to use a guard to ensure main is not run when being imported by another script</p></li>\n<li><p><a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"noreferrer\"><code>tempfile</code></a></p>\n\n<p>As mentioned by @Toby already, there is module for creating Temporary files/directories</p></li>\n<li><p>Why does it need to be in a file though?</p>\n\n<p>You could create a list of filenames and poll for changes</p>\n\n<p>And compare the lists instead of the files</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:01:20.297",
"Id": "409074",
"Score": "0",
"body": "It doesn't have to be stored in a file. I just thought it would be better than storing it in RAM the whole time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T00:46:40.287",
"Id": "409118",
"Score": "3",
"body": "@tjt263 Why would it?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T14:29:32.423",
"Id": "211554",
"ParentId": "211546",
"Score": "5"
}
},
{
"body": "<p>This script might get the job done, but it is a rather crude and inefficient hack. Ideally, you should avoid polling every quarter second (or polling at all). Also, I see no reason to write any files to <code>/tmp</code>.</p>\n\n<hr>\n\n<p>The ideal way to do it in Linux is to use udev. If you don't want to <a href=\"http://reactivated.net/writing_udev_rules.html\" rel=\"noreferrer\">write a persistent udev rule</a>, or you don't have root access, you can run <code>/sbin/udevadm monitor --udev --property</code> as a child process, and trigger your test whenever <code>udevadm</code> offers output. For a smarter script, you can can look for the <code>ACTION=add</code> line and take advantage of the information in the <code>SUBSYSTEM=…</code> and <code>DEVPATH=…</code> lines. <code>DEVPATH</code> tells you path to the device within <code>/sys</code>. But, even if you simply trigger your script only when any output appears, that would be a huge improvement over polling four times a second.</p>\n\n<pre><code>import itertools\nfrom subprocess import Popen, PIPE\nimport re\nimport sys\n\nKEYVALUE_RE = re.compile(r'([^=]+)=(.*)')\n\ndef events(stream):\n \"\"\"\n Read udev events from the stream, yielding them as dictionaries.\n \"\"\"\n while True:\n event = dict(\n KEYVALUE_RE.match(line).groups()\n for line in itertools.takewhile(KEYVALUE_RE.match, stream)\n )\n if event:\n yield event\n\ntry:\n UDEVADM = ['/sbin/udevadm', 'monitor', '--udev', '--property']\n with Popen(UDEVADM, stdout=PIPE, encoding='UTF-8') as udevadm:\n for event in events(udevadm.stdout):\n if event['ACTION'] == 'add' and event.get('DRIVER') == 'usb-storage':\n print(event)\n break\nexcept KeyboardInterrupt:\n sys.exit(1)\n</code></pre>\n\n<hr>\n\n<p>On macOS, you can get similar information by running and monitoring the output of <code>/usr/sbin/diskutil activity</code>, if you are interested in storage devices. Look for lines starting with <code>***DiskAppeared</code>.</p>\n\n<pre><code>from subprocess import Popen, PIPE\nimport sys\n\ntry:\n DISKUTIL = ['/usr/sbin/diskutil', 'activity']\n with Popen(DISKUTIL, stdout=PIPE, encoding='UTF-8') as diskutil:\n # Ignore events that describe the present state\n for line in diskutil.stdout: \n if line.startswith('***DAIdle'): \n break\n # Detect the first subsequent \"Disk Appeared\" event \n for line in diskutil.stdout:\n if line.startswith('***DiskAppeared'):\n print(line)\n break\nexcept KeyboardInterrupt:\n sys.exit(1)\n</code></pre>\n\n<p>If you are interested in non-storage devices as well, then you could take advantage of the <a href=\"https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html\" rel=\"noreferrer\">File System Events API</a>, possibly through the <a href=\"https://pypi.org/project/MacFSEvents/\" rel=\"noreferrer\">MacFSEvents</a> Python package or the cross-platform <a href=\"https://github.com/emcrisostomo/fswatch/wiki\" rel=\"noreferrer\">fswatch</a> program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:48:09.177",
"Id": "211568",
"ParentId": "211546",
"Score": "12"
}
},
{
"body": "<p>Another point I didn't see mentioned:</p>\n\n<pre><code>try:\n os.mkdir('/tmp/dev')\nexcept FileExistsError:\n pass\n</code></pre>\n\n<p><code>except</code> blocks with <code>pass</code> are usually a sign that there is probably a better way. In this case, assuming you are using Python 3.2 or later, is to use <a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"nofollow noreferrer\"><code>os.makedirs</code></a> with the <code>exist_ok</code> argument set to <code>True</code>:</p>\n\n<pre><code>os.makedirs('/tmp/dev', exist_ok=True)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:48:30.247",
"Id": "409109",
"Score": "0",
"body": "Why's that better? What's the difference?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:21:07.270",
"Id": "211570",
"ParentId": "211546",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T13:48:13.767",
"Id": "211546",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x",
"linux",
"macos"
],
"Title": "Reporting new USB storage devices on Linux and macOS with Python"
} | 211546 |
<p>Emacs command for quick substitution of previously-typed character. This is supposed to help input umlauts quicker by switching letters to their analogues and so on.</p>
<pre><code>(defun krv/last-char-check (&optional pos)
"Find previous non-whitespace character in current string.
Return in form of (position . character) cons nor nil"
(save-excursion
(let ((cur-pos (or (and pos (goto-char pos))
(point))))
(loop for prev-char = (preceding-char) then (preceding-char)
for back-pos = 0 then (1- back-pos)
when (bolp) return nil
; known whitespaces listed
unless (member prev-char (list ?\ ?\xA0 ?\t)) return (cons back-pos prev-char)
else do (backward-char)))))
(defun krv/unwrap-list-to-alist (list-form)
"Helper function for setting character substitutions"
(loop with first = (car list-form)
for (s1 s2 . nil) on list-form
if s2 collect (cons s1 s2)
else collect (cons s1 first)))
(defvar cycle-symbols-alist nil
"list of characters used for symbol cycling")
(defgroup cycle-symbols nil
"Group for cycling symbols")
(defcustom cycle-symbols-lists-default
(list (list ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?0) (list ?+ ?-) (list ?> ?< ?=))
"Default lists for symbol cycling"
:type 'sexp
:set (lambda (s val)
(set-default s val)
(setq cycle-symbols-alist (mapcan #'unwrap-list-to-map val))))
(defun krv/cycle-symbols-command ()
"Cycle previous non-whitespace if there is a known substitution"
(interactive)
(let* ((check-pair (krv/last-char-check))
(pos (car check-pair))
(char (cdr check-pair))
(rchar (assoc char cycle-symbols-alist)))
(when (and check-pair rchar)
(forward-char pos)
(delete-backward-char 1)
(insert-char (cdr rchar))
(backward-char pos))))
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T14:46:23.723",
"Id": "211556",
"Score": "1",
"Tags": [
"elisp"
],
"Title": "Swap previous non-whitespace character in emacs buffer with some known analogue"
} | 211556 |
<p>In reference to my previous code:
<a href="https://codereview.stackexchange.com/questions/211040/user-class-getting-user-data-logging-in-secure-csrf-session-handling">User class: getting user data, logging in, secure CSRF session handling</a></p>
<p>I re-wrote my SystemUser class, without the DI container (for now), I'm still trying to figure out how to structure my code to work with dependency injections container rather than a singletone. </p>
<p>I wrote my code basically after looking at <a href="https://codereview.stackexchange.com/questions/170961/user-class-taking-on-login-and-registration-capabilities">this example</a> and inspired by <a href="https://codereview.stackexchange.com/questions/201066/should-i-add-the-fetch-group-method-to-my-user-class-or-should-i-create-a-sepa">this post</a> I found, while trying to follow the SOLID principals and PSR standards, focusing on the structure and architecture (I would rather prefer to focus on the code architecture, since I was told that my code "is far from being good" without explaining why :[ )</p>
<p>SystemUser.php </p>
<pre><code><?php
namespace MyApp\Models;
class SystemUser
{
public $id;
public $firstName;
public $lastName;
public $userName;
public $email;
public $lastLogin;
public $customerName;
public $password;
public $ip;
public $loginTimestamp;
public $isLoggedIn;
# @obj SystemUser profile information (fullname, email, last_login, profile picture, etc')
public $systemUserDetatils;
# @obj SystemUser Login data (a template for a login insert)
public $systemUserLogin;
# @obj SystemUser Authenticator object
protected $systemUserAuthenticator;
# @obj SystemUser Logout handling
protected $systemUserLogout;
# @obj Handle SystemUser Sessions (Sets user sessions, Check if sessions are set, Check timeout, ect')
public $systemUserSessions;
/*===============================
= Methods =
================================*/
/**
*
* Construct
* @param $systemUserId Int (optional) User Id
*
*/
public function __construct($systemUserId = NULL)
{
# Create systemUserDedatils obj
$this->systemUserDetatils = new \MyApp\Models\SystemUser\SystemUserDetails();
# If system_user passed
if ( $systemUserId ) {
# Set system user ID
$this->id = $systemUserId;
# Get SysUser data
$this->systemUserDetatils->get($this);
} else {
# Check for sysUser id in the session:
$systemUserId = $this->systemUserDetatils->getUserFromSession();
# Get user data from session
if ( $systemUserId ) {
# Set system user ID
$this->id = $systemUserId;
# Get SysUser data
$this->systemUserDetatils->get($this);
}
}
}
/**
*
* Set Login: Sets the SystemUserLogin object to $systemUserLogin variable.
* @param $_systemUserLogin SystemUserLogin Gets a SystemUserLogin object
*
*/
public function setSystemUserLogin(\MyApp\Models\SystemUser\SystemUserLogin $_systemUserLogin)
{
$this->systemUserLogin = $_systemUserLogin;
}
/**
*
* System User Login
* @return
*
*/
public function login()
{
$this->systemUserAuthenticator = new \MyApp\Models\SystemUser\SystemUserAuthenticator();
return $this->systemUserAuthenticator->login($this);
}
/**
*
* Logout: Now guess what this method does..
*
*/
public function logout()
{
$this->systemUserLogout = new \MyApp\Models\SystemUser\SystemUserLogout($this);
}
/**
*
* Checks if a user is logged in
* @return
*
*/
public function isLoggedIn()
{
return $this->systemUserSessions->isLoggedIn($this);
}
/**
*
* Checks if a system user has a timeout
* @return
*
*/
public function checkTimeout()
{
return $this->systemUserSessions->isTimeout($this);
}
}
</code></pre>
<p>SystemUserDetails.php </p>
<pre><code><?php
namespace MyApp\Models\SystemUser;
use MyApp\Core\Database;
use MyApp\Core\Config;
use MyApp\Helpers\Session;
class SystemUserDetails
{
private $db;
/**
*
* Construct
*
*/
public function __construct(/*Database $db*/)
{
# Get database instance
$this->db = Database::getInstance();
// $this->db = $db;
}
/**
*
* Find method: Find user by id or by username
* @param $user String / Init A username or user ID
* @return
*
*/
public function get(\MyApp\Models\SystemUser $systemUser)
{
if ($systemUser->id) {
# Enable search for a system_user by a string name or if numeric - so by id
$field = ( is_numeric($systemUser->id) ) ? 'system_user_id' : 'uname';
# Search for the system_user in the Database 'system_users' table.
$result = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE {$field} = :sys_user", array('sys_user' => $systemUser->id));
# If there is a result
if ( $result ) {
# Set result
$this->set($systemUser, $result);
return true;
} else {
return false;
}
}
else {
return false;
}
}
/**
*
* Set User data to $this obj
* @param $userData Array User data fetched from the db (usually by the find method)
* @return
*
*/
public function set(\MyApp\Models\SystemUser $systemUser, Array $userData)
{
$systemUser->id = $userData['system_user_id'];
$systemUser->firstName = $userData['fname'];
$systemUser->lastName = $userData['lname'];
$systemUser->userName = $userData['uname'];
$systemUser->email = $userData['email'];
$systemUser->lastLogin = $userData['last_login'];
}
/**
*
* Get User from session
* @param
* @return
*
*/
public function getUserFromSession()
{
# Check if there is a session user id set
if (Session::exists(Config::$systemUserId)) {
# Insert session data to system_user variable
return Session::get(Config::$systemUserId);
} else {
# Returning false cause there is no user id session
return false;
}
}
}
</code></pre>
<p>SystemUserLogin.php </p>
<pre><code><?php
namespace MyApp\Models\SystemUser;
/**
*
* System User Login - Prepare a user for login with this class.
*
*/
class SystemUserLogin
{
public $customerName;
public $userName;
public $password;
public $userIp;
/**
*
* Construct - Set customer, username and password
* @param $_customerName String
* @param $_userName String
* @param $_password String
*
*/
public function __construct(String $_customerName, String $_userName, String $_password)
{
$this->customerName = $_customerName;
$this->userName = $_userName;
$this->password = $_password;
$this->userIp = \MyApp\Helpers\General::getIp();
}
}
</code></pre>
<p>SystemUserAuthenticator.php: </p>
<pre><code> <?php
namespace MyApp\Models\SystemUser;
use MyApp\Core\Database;
use MyApp\Core\Config;
use MyApp\Helpers\Session;
class SystemUserAuthenticator
{
private $db;
/**
*
* Construct
*
*/
public function __construct(/*Database $db*/)
{
# Get database instance
$this->db = Database::getInstance();
// $this->db = $db;
}
/**
*
* Login method
* @param $customer_name String Get a customer_name user input
* @param $username String Get a username user input
* @param $password String Get a password user input
* @return Boolian Is this a signed System user?
*
*/
public function login(\MyApp\Models\SystemUser $systemUser)
{
# Create a Customer Obj
$customer = new \MyApp\Models\Customer($systemUser->systemUserLogin->customerName);
try {
# Check customer result
if ( (!isset($customer)) || (!isset($customer->dbName)) || (!isset($customer->host)) )
throw new \MyApp\Core\Exception\Handler\LoginException("Bad company name: {$systemUser->systemUserLogin->customerName}");
# Connect to new database
$newConnection = $this->db->customer_connect($customer->host, $customer->dbName);
# If status is connected
if ($newConnection) {
# Check for user credentials data
$userData = $this->systemUserLoginValidation($systemUser->systemUserLogin->userName, $systemUser->systemUserLogin->password);
# If the result isn't a valid array - EXEPTION
if ( (!is_array($userData)) || (empty($userData)) )
throw new \MyApp\Core\Exception\Handler\LoginException("Customer: '{$systemUser->SystemUserLogin->customerName}' - Invalid username ({$systemUser->SystemUserLogin->userName}) or password ({$systemUser->SystemUserLogin->password})");
# Store Customer in the sesison
Session::put(Config::$customer, serialize($customer));
# Set data for this System_user object
$this->set($systemUser, $userData);
# Set a login session for the user id:
Session::put(Config::$systemUserId, $systemUser->id);
# Set logged in user sessions
// $this->setLoggedinUserSessions($systemUser);
$systemUser->systemUserSessions = new \MyApp\Models\SystemUser\SystemUserSessions();
$systemUser->systemUserSessions->setSecuritySession($systemUser);
# Update last_login for this user
$this->updateLastLogin($systemUser->id, $systemUser->loginTimestamp);
// return $this;
return true;
} else {
# Connect back to backoffice (current db set)
$this->db->connect_to_current_set_db();
throw new \MyApp\Core\Exception\Handler\LoginException('User does not exist');
return false;
}
} catch (\MyApp\Core\Exception\Handler\LoginException $e) {
$e->log($e);
return false;
// die(General::toJson(array( 'status' => false, 'message' => 'Bad login credentials.' )));
}
}
/**
*
* Set User data to $this obj
* @param $userData Array User data fetched from the db (usually by the find method)
* @return
*
*/
public function set(\MyApp\Models\SystemUser $systemUser, Array $userData)
{
# Sets basic user data using SystemUserDetails
$systemUser->systemUserDetatils->set($systemUser, $userData);
# Set Login data
$systemUser->loginTimestamp = date("Y-m-d H:i:s");
$systemUser->isLoggedIn = true;
$systemUser->ip = $systemUser->systemUserLogin->userIp;
}
/**
*
* Check if user exist in 'system_users' table
* @param $username String Get a username user input
* @param $password String Get a password user input
* @return Array/Boolian Is this a signed System user?
*
*/
private function systemUserLoginValidation(String $username, String $password)
{
$userData = $this->db->row("SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password", array('username' => $username, 'password' => sha1($password)));
if ($userData)
return $userData;
else
return false;
}
/**
*
* Updates the system users "last logged in" field in db
* @param $id Int System User ID
* @param $date String Current login timestamp (set to $systemUser->loginTimestamp)
*
*/
private function updateLastLogin(Int $id, String $date)
{
$this->db->row("UPDATE system_users SET last_login = :newLastLogin WHERE system_user_id = :systemUserId", array('newLastLogin' => $date, 'systemUserId' => $id));
}
}
</code></pre>
<p>SystemUserSessions.php : </p>
<pre><code><?php
namespace MyApp\Models\SystemUser;
use MyApp\Core\Config;
use MyApp\Helpers\Session;
use MyApp\Helpers\Token;
use MyApp\Helpers\Hash;
use MyApp\Helpers\General;
use MyApp\Models\SystemUser;
/**
*
* System User Security Session: Handle the system user security session / token / secret / ect.
*
*/
class SystemUserSessions
{
/**
*
* Sets SystemUser security session
* @param $ystemUser Obj SystemUser object
*
*/
public function setSecuritySession(SystemUser $systemUser)
{
$this->setLoggedinUserSessions($systemUser);
}
/**
*
* Check if there is a logged in user
* @param $ystemUser Obj SystemUser object
*
*/
public function isLoggedIn(SystemUser $systemUser)
{
if ( Session::exists(Config::$secret) && # Secret session exists
Session::exists(Config::$session_id) && # Session_id session exists
Session::exists(Config::$systemUserId) && # User session exists
Session::exists(Config::$is_logged_in) # Check if 'logged in' session exists
)
{
# Get users ip
$ip = General::getIp();
# if the saved bombined session
if (
(Session::get(Config::$combined) === Hash::make_from_array(array(Session::get(Config::$secret), session_id()), $ip)) &&
(Session::get(Config::$is_logged_in) === true )
)
{
# Set ip to system user object
$systemUser->ip = $ip;
return true;
} else {
return false;
}
}
else {
return false;
}
}
/**
*
* Check if loggin session is timeout
* @param $ystemUser Obj SystemUser object
*
*/
public function isTimeout(SystemUser $systemUser)
{
if (Session::exists(Config::$login_timestamp)){
# Calculate time
$session_lifetime_seconds = time() - Session::get(Config::$login_timestamp) ;
if ($session_lifetime_seconds > Config::MAX_TIME){
$systemUser->logout();
return true;
} else {
return false;
}
} else {
$systemUser->logout();
return false;
}
}
/**
*
* Set sessions for the logged in user.
* Tutorial: http://forums.devshed.com/php-faqs-stickies/953373-php-sessions-secure-post2921620.html
* @param $systemUser Object Gets the main SystemUser class object
*
*/
private function setLoggedinUserSessions(SystemUser $systemUser)
{
# Generate security sessions
$this->generateSecuritySessions($systemUser);
# Set login timestamp
Session::put(Config::$login_timestamp, $systemUser->loginTimestamp);
# Set login flag to true
Session::put(Config::$is_logged_in, true);
# Set login IP
Session::put(Config::$login_user_ip, $systemUser->ip);
}
/**
*
* Generate system user security sessions
* @param $new_session Boolean (optinal) Dedices if to delete the cookie session id [default is set to true]
*
*/
public function generateSecuritySessions(SystemUser $systemUser, bool $newSession = true)
{
if ($newSession)
# Generate a new session ID
session_regenerate_id(true);
# Fetch cookie session ID
$sessionId = session_id();
# Set the session id to the session
Session::put(Config::$session_id, $sessionId);
# Create a secret token
# Set it in session (does them both)
$secret = Token::generate_login_token();
# Combine secret and session_id and create a hash
$combined = Hash::make_from_array(array($secret, $sessionId, $systemUser->ip));
# Add combined to session
Session::put(Config::$combined, $combined);
}
}
</code></pre>
<p>SystemUserLogout.php: </p>
<pre><code><?php
namespace MyApp\Models\SystemUser;
use MyApp\Helpers\Session;
use MyApp\Helpers\Cookie;
class SystemUserLogout
{
/**
*
* Construct - Set customer, username and password
*
*/
public function __construct()
{
# Delete cookies
Cookie::eat_cookies();
# Delete all sessions
Session::kill_session();
# Re-generate SESSIONID
session_regenerate_id(true);
}
}
</code></pre>
<p><em>Huge thank you to @John Conde</em></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:44:46.647",
"Id": "409204",
"Score": "0",
"body": "Hi Rick, im not sure how best to help you - the code is really convoluted, so its hard to work out whats going on, or indeed what the overall purpose is. The main issue i think is that you are writing procedural code, and wrapping it in classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:46:10.930",
"Id": "409206",
"Score": "0",
"body": "Is your main objective to learn OOP, or create a usable product? Are you new to just OOP, or programming in general"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:59:23.873",
"Id": "409210",
"Score": "0",
"body": "@Steve I'm not sure what's the exact definition of \"procedural code\". My main objective is to learn OOP. I'm new to OOP in a certain way, I used CodeIgniter most of the time, but never got into writing an MVC or understanding how it works. Most tutorials/courses (Udemy/Blogs/CodeAcademy/Lynda) use weird examples like \"cars\" / \"clothes\", and the more practical examples don't use OOP, or at least not in a \"serious\" way. Or just teach a framework where all is already built. Please do try to review my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:09:45.553",
"Id": "409213",
"Score": "0",
"body": "Ok, thanks for answering - i was just checking that you werent trying to create an actual product, else i would suggest picking up symfony or laravel and utilizing the huge communities and documentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:11:23.130",
"Id": "409215",
"Score": "0",
"body": "To take a step back, are you using any 3rd party libraries, or trying to build a complete system from scratch? Do you have a single entrypoint (usually an `index.php`) the bootstraps the application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:12:21.207",
"Id": "409217",
"Score": "0",
"body": "Can I ask why? I mean, why shouldn't I do this if it's a real world project, and use symfony/laravel? Don't they do the same?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:13:39.943",
"Id": "409218",
"Score": "0",
"body": "Oh i didnt mean you cant or shouldnt create your own systems, i do often. I just meant if you had a boss breathing down your neck, its going to be a thousand times quicker to get a usuable, maintainable application witha framework"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:16:28.060",
"Id": "409220",
"Score": "0",
"body": "And i asked about libraries, because it would give me context, which would help me to help you - its totally fine to create everything from scratch as a learning excersise, it just means that without access to the complete code, i wont know exactly how it all fits together. I dont suppose you have a github with your code do you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:18:11.950",
"Id": "409221",
"Score": "0",
"body": "\"are you using any 3rd party libraries\" - yes, currently using monolog for logging. whoops for error handling (that runs only for a local server). and symfony DI that I'm currently trying to learn. I'm trying to build a complete system *almost* from scatch. I do use an index.php that loads the Whoops library (-> loads Monologe within Whoops), require compser autoload.php file, Soon will add the container, App class that leads to a VueRouter (handle the routing there)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:19:07.397",
"Id": "409222",
"Score": "0",
"body": "Do you want me to add my index.php, init.php, App.php and login controller classes? I mean, would that help you to guide me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:20:23.027",
"Id": "409223",
"Score": "0",
"body": "It would help, but im not sure that amount of code is OK for this website - a github link would be much better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:31:04.290",
"Id": "409227",
"Score": "0",
"body": "OK, @ reply here when you have done it, so i remember to check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:47:26.400",
"Id": "409229",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Please post a follow-up question linking back to your original question instead, when you've finished writing it all down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:48:10.463",
"Id": "409231",
"Score": "0",
"body": "Keep in mind that all code up for review should be included in the question itself. A project with repository can be added, sure, but only for bonus context. It will not be up for review. Please take a look at the [help/on-topic] if you have questions about what is and isn't permissible (CC @Steve)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:56:20.290",
"Id": "409234",
"Score": "0",
"body": "@Mast yes, its just for context, though im 99% sure the main issue is poor architecture based on a lack of understanding of DI and IOC, and more generally OOP, so codereview might not be the best place for this. Im not sure there is actually any suitable Stack site? But i would like to help the OP if i can"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:00:16.483",
"Id": "409236",
"Score": "0",
"body": "@Mast also, why did you remove the edit showing usage - thats fairly important context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:02:50.073",
"Id": "409238",
"Score": "0",
"body": "@Steve Because it should be part of the next question, not this one. It has been answered now, it's all explained in the link. Should OP post a new question, it's absolutely fine for you to help them there."
}
] | [
{
"body": "<p>For me, there is way too much code to review. So I could make just a brief outline. </p>\n\n<p>first of all, I think here you inclined to the opposite extremity, creating classes with no methods other than constructor. I don't think it's a good move. So I would take Login and Logout back into the main class as methods.</p>\n\n<p>There are many places that can be written more efficiently. For example,</p>\n\n<pre><code> $userData = $this->db->row(\"SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password\", array('username' => $username, 'password' => sha1($password)));\n\n if ($userData)\n return $userData;\n else\n return false;\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>return $this->db->row(\"SELECT system_user_id, fname, lname, uname, email, last_login FROM system_users WHERE uname = :username AND password = :password\", array('username' => $username, 'password' => sha1($password)));\n</code></pre>\n\n<p>on a side note, as you can see, it is very hard to read (and review) such big lines. You must split your code so it would fit for the screen: </p>\n\n<pre><code>$sql = \"SELECT system_user_id, fname, lname, uname, email, last_login \n FROM system_users WHERE uname = :username AND password = :password\";\n$data = array('username' => $username, 'password' => sha1($password));\nreturn $this->db->row($sql, $data);\n</code></pre>\n\n<p>and now it was revealed that you are using an outdated and insecure approach to hashing passwords. You must hash them using <a href=\"http://php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">password_hash()</a> and verify using password_verify(). I've got a handy example for this, <a href=\"https://phpdelusions.net/pdo_examples/password_hash\" rel=\"nofollow noreferrer\">Authenticating a user using PDO and password_verify()</a>.</p>\n\n<p>Another example of rather heavily duplicated code, a literal example of the WET acronym (Write Everything Twice) is SystemUser's constructor. Why not to make it this way</p>\n\n<pre><code>public function __construct($systemUserId = NULL)\n{\n $this->id = $systemUserId ?? $this->systemUserDetatils->getUserFromSession();\n $this->systemUserDetatils = new \\MyApp\\Models\\SystemUser\\SystemUserDetails();\n if ( $this->id ) {\n $this->systemUserDetatils->get($this);\n }\n}\n</code></pre>\n\n<p>So here we are effectively writing everything once, making our code DRY (Don't Repeat Yourself) by fist setting <code>$this->id</code> to either <code>$systemUserId</code> if it's set or whatever <code>$this->systemUserDetatils->getUserFromSession()</code> returns otherwise, and then populating the user details. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:45:07.987",
"Id": "409205",
"Score": "0",
"body": "Thanks a lot for your review, you are one of my favorite users on codereview! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:48:54.677",
"Id": "409208",
"Score": "0",
"body": "I split the code for the login because I have a validation in the controller (before passing the variables to the login model), and thing I'm going to move my validation to there - so I wont have only one function for the login. For the Logout, I wrote it that way because I'm sure I'm going to add and run more functions to run before I log a user out, so this is just the infrastructure for a bigger thing I'm planning on. for the rest of your comments I'll have to review later in compare to my code, so if i'll have anything to comment on, you'll know.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:30:22.670",
"Id": "211620",
"ParentId": "211557",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:01:11.147",
"Id": "211557",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"design-patterns"
],
"Title": "User class: getting user data, logging in, secure CSRF session handling, logging out"
} | 211557 |
<p>In order to improve my understanding of C++ template meta-programming, SFINAE, references, and overall class design, I've tried to implement a <code>Maybe<T></code> class in C++.</p>
<p>Of course, the class is heavily based off of Haskell's <code>Maybe</code> Monad, and has the same functionality. I am aware that <code>std::optional<T></code> pretty much does the same thing in C++17, but I decided not to implement it exactly as the standard specifies. </p>
<p>In specific, I've renamed a few functions, and added some of my own (namely, the <code>apply</code> method). More notably, I tried to make it support possible references (by making it use a <code>std::reference_wrapper</code>).</p>
<p>Here is the code below:</p>
<p>maybe.hpp:</p>
<pre><code>#pragma once
#include <utility>
#include <exception>
#include <type_traits>
#include <functional>
namespace maybe {
struct nothing_t {} nothing;
template <typename T>
class Maybe_Base {
public:
struct bad_access : std::exception {
virtual const char* what() const noexcept {
return "Attempted to access a value of a Maybe wrapper that doesn't exist.";
}
};
Maybe_Base():
val(nullptr)
{}
Maybe_Base(nothing_t):
val(nullptr)
{}
template <class... Args>
explicit Maybe_Base(Args&&... args) {
val = new T(std::forward<Args>(args)...);
}
~Maybe_Base() {
if (val)
val->~T();
delete val;
}
// Is there a way to ensure extraneous copies aren't made? Or is the only option just to delete the copy constructor entirely?
Maybe_Base(const Maybe_Base<T>& other) {
if (other.val)
val = new T(*other.val);
else
val = nullptr;
}
Maybe_Base& operator=(Maybe_Base<T> other) {
swap(*this, other);
return *this;
}
friend void swap(Maybe_Base<T>& a, Maybe_Base<T>& b) {
using std::swap;
swap(a.val, b.val);
}
Maybe_Base(Maybe_Base<T>&& other) {
this->val = other.val;
other.val = nullptr;
}
inline bool empty() const {
return val == nullptr;
}
inline bool hasValue() const {
return !empty();
}
inline explicit operator bool() const {
return hasValue();
}
T value() {
if (empty())
throw bad_access();
else
return *val;
}
T valueOr(T defaultVal) {
if (empty())
return defaultVal;
return *val;
}
const T& operator*() const {
return *val;
}
T& operator*() {
return *val;
}
const T* operator->() const {
return val;
}
T* operator->() {
return val;
}
void clear() {
val->~T();
delete val;
val = nullptr;
}
template <class Func, typename... Args>
std::enable_if_t< !std::is_void_v<std::invoke_result_t<Func, T, Args...>>
&& !std::is_member_function_pointer_v<Func>,
Maybe_Base<std::invoke_result_t<Func, T, Args...>>
>
apply(Func f, Args&&... args) {
if (*this)
return Maybe_Base<std::invoke_result_t<Func, T, Args...>>{f(this->value(), std::forward<Args>(args)...)};
return nothing;
}
template <class Func, typename... Args>
std::enable_if_t< std::is_void_v<std::invoke_result_t<Func, T, Args...>>
&& !std::is_member_function_pointer_v<Func>,
void
>
apply(Func f, Args&&... args) {
if (*this)
f(this->value(), std::forward<Args>(args)...);
}
template <class Pointer_To_Method, typename... Args>
std::enable_if_t< !std::is_void_v<std::invoke_result_t<Pointer_To_Method, T, Args...>>
&& std::is_member_function_pointer_v<Pointer_To_Method>,
Maybe_Base<std::invoke_result_t<Pointer_To_Method, T, Args...>>
>
apply(Pointer_To_Method f, Args&&... args) {
if (*this)
return Maybe_Base<std::invoke_result_t<Pointer_To_Method, T, Args...>>{(this->value().*f)(std::forward<Args>(args)...)};
return nothing;
}
template <class Pointer_To_Method, typename... Args>
std::enable_if_t< std::is_void_v<std::invoke_result_t<Pointer_To_Method, T, Args...>>
&& std::is_member_function_pointer_v<Pointer_To_Method>,
void
>
apply(Pointer_To_Method f, Args&&... args) {
if (*this)
(this->value().*f)(std::forward<Args>(args)...);
}
private:
T* val;
};
template <class T, bool = std::is_reference_v<T>>
class Maybe;
template <class T>
class Maybe<T, false> : public Maybe_Base<T> {
public:
template <typename... Args>
Maybe(Args&&... args): Maybe_Base<T>(std::forward<Args>(args)...) {}
};
template <class T>
class Maybe<T, true> : public Maybe_Base<std::reference_wrapper<std::decay_t<T>>> {
typedef std::reference_wrapper<std::decay_t<T>> Wrap_Type;
public:
template <typename... Args>
Maybe(Args&&... args): Maybe_Base<Wrap_Type>(std::ref(args)...) {}
T value() {
return Maybe_Base<Wrap_Type>::value().get();
}
};
} // namespace maybe
</code></pre>
<p>And here's a small test .cpp file to make sure the implementation works:</p>
<pre><code>#include <iostream>
#include <memory>
#include <optional>
#include "maybe.hpp"
struct foo {
int i;
foo(int i_): i(i_) {}
foo() {}
void bar(int j) {
std::cout << "Bar." << ' ' << i*j << std::endl;
}
~foo() {
std::cout << "Deleting a foo..." << std::endl;
}
};
maybe::Maybe<char> letter(int i) {
if (i >= 0 && i < 26)
return maybe::Maybe<char>(i + 'A');
return maybe::nothing;
}
int main() {
maybe::Maybe<std::unique_ptr<foo>> i{ std::make_unique<foo>(8) };
maybe::Maybe<std::unique_ptr<foo>> j = std::move(i);
maybe::Maybe<foo> f{12321};
std::cout << std::boolalpha << j.hasValue() << ' ' << i.hasValue() << std::endl;
f.apply(&foo::bar, 2);
int p = 7;
maybe::Maybe<int&> q = p;
std::cout << q.value() << std::endl;
p = 8;
std::cout << q.value() << std::endl;
// Could I possibly do something simpler like `q = 6`?
q.value() = 6;
std::cout << p << std::endl;
q.apply([] (int a) { std::cout << a << std::endl; });
std::cout << q.apply([] (int a) { return a + 1; }).value();
maybe::Maybe<char> c = letter(12);
std::cout << c.value() << std::endl;
}
</code></pre>
<p>Is there anything that I seem to have messed up, or situations I've overlooked? I'm specifically concerned in making sure that the implementation is efficient, and has easy use.</p>
| [] | [
{
"body": "<ul>\n<li><p>Use <code>std::unique_ptr</code>. (It's much safer and easier than manual memory management).</p></li>\n<li><p><em>bug:</em> The <code>delete</code> operator will call the object destructor. We should not call the destructor manually. (A perfect example of why we should use <code>std::unique_ptr</code> and avoid this entirely :D ).</p></li>\n<li><p>Note that <code>std::optional</code> doesn't allocate memory itself, but keeps the contained object on the stack. This could be done with a boolean flag and <code>std::aligned_storage</code> or perhaps with <code>std::variant</code>.</p></li>\n<li><p><code>value</code> and <code>valueOr</code> can be <code>const</code> functions. <code>value</code> should perhaps return a reference, and have const and non-const versions.</p></li>\n<li><p><em>opinion:</em> I really dislike that <code>std::optional</code> overloads <code>operator-></code> and <code>operator*</code>. They're unnecessary and make it less obvious what the type is. It's not a pointer type (at least semantically), so I don't think they make sense. Personally I'd skip them.</p></li>\n<li><p>If we're creating a special case for reference types, and hiding the <code>std::reference_wrapper</code> internally, we need to re-implement the other access functions, not just <code>value()</code>. Currently the <code>reference_wrapper</code> is exposed through <code>valueOr</code>, <code>operator*</code> and <code>operator-></code>.</p>\n\n<p>(This results in a subtly different implementation for \"reference maybes\", and I don't know if that's a good thing or not. However, I feel like we should either hide the <code>std::reference_wrapper</code> entirely, or let the user create a <code>Maybe<std::reference_wrapper<T>></code> themselves if they need one).</p></li>\n<li><p>The <code>apply</code> methods are very interesting. :)</p>\n\n<ul>\n<li><p>I think we need <code>const</code> versions (for calling <code>const</code> member functions of types contained in <code>const Maybe</code>'s).</p></li>\n<li><p>Since the <code>Maybe</code> can also store simple POD types, where the <code>apply</code> functions do not make sense, perhaps <code>apply</code> should be implemented as a set of free functions (and named <code>invoke_maybe</code> or something similar). This would provide a calling syntax more consistent with <code>std::invoke</code> and <code>std::bind</code>. It would also allow <code>invoke_maybe</code> to be implemented for other classes, such as <code>std::function</code> (or <code>std::optional</code>), returning an empty <code>Maybe</code> if necessary.</p></li>\n<li><p><em>feature request:</em> Note that <a href=\"https://en.cppreference.com/w/cpp/utility/functional/invoke\" rel=\"nofollow noreferrer\"><code>std::invoke</code></a> lets us access member variables, not just member functions. This doesn't appear to be supported with the current <code>apply</code> implementation, but would be pretty cool.</p></li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T02:32:11.003",
"Id": "409119",
"Score": "0",
"body": "Thank you for the feedback! I'll be making the changes you mentioned. A few questions though: \n1) Why is it bad to call the destructor manually? I understand it's better to use a unique_ptr overall, but why is it specifically a bug to call the destructor manually?\n2) For the assignment operators, I tried using the copy-and-swap idiom. Does this only apply to copy-assignments? I thought it was supposed to implement both assignment operators, to simply the code. Am I correct, or did I use CAS wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:14:34.030",
"Id": "409144",
"Score": "2",
"body": "1) Since `delete` calls the destructor itself, we end up with two destructor calls, which is undefined behaviour. (Everything in C++ depends on having one destructor call. Once that happens, the object lifetime is deemed to have ended.) 2) You're quite right. My bad."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:33:42.917",
"Id": "211575",
"ParentId": "211558",
"Score": "5"
}
},
{
"body": "<p>To be frank, I'm not sure it really is a <code>Maybe</code> implementation. It's actually not very different from a smart pointer (well, maybe not that smart since the destructor deletes the underlying value twice, as @user673679 points out :). By the way I don't think that a smart pointer -or any pointer- is a bad approximation of the Haskell <code>Maybe</code> type: it can be either <code>nullptr</code> (<code>Nothing</code>) or pointing to some value (<code>Just some_value</code>). Of course, <code>std::optional</code> would probably be more efficient, since it stores the optional value on the stack, but I don't believe it's a conceptual leap towards <code>Maybe</code> either: the real difference between pointers and <code>std::optional</code> on the one hand, and <code>Maybe</code> on the other hand is that <code>Maybe</code> is a sum type, that is a type that can be either one of different types, whereas pointers or <code>std::optional</code> are types with a well-defined null/void value.</p>\n\n<p>Implementing sum types in C++ is rather difficult. The standard library's sum type -<code>std::variant</code>- is rather cumbersome and has drawn convincing <a href=\"https://bitbashing.io/std-visit.html\" rel=\"nofollow noreferrer\">complaints</a>. But it's also a path to a lot more power than you could reach with pointers or optional: they can be a good approximation of <code>Maybe</code>, but not of <code>Either</code>, for instance, which isn't fundamentally different though, and a lot more powerful.</p>\n\n<p>So what would <code>Maybe</code> as a sum type look like in C++? I would say something like:</p>\n\n<pre><code>#include <variant>\n\nstruct Nothing {};\n\ntemplate <typename T>\nstruct Just {\n Just(const T& t) : value(t) {}\n Just(T&& t) : value(t) {}\n Just() = default;\n\n T value; \n};\n\ntemplate <typename T>\nusing Maybe = std::variant<Nothing, Just<T>>;\n</code></pre>\n\n<p>So, how would you use it then? Creating one looks very much like what you did:</p>\n\n<pre><code>Maybe<char> letter(int i) {\n if (i >= 0 && i < 26) return Just<char>('A' + i);\n return Nothing();\n}\n</code></pre>\n\n<p>Now, what can you do with it? <code>Maybe</code> is a functor in the Haskell sense, so you need a way to map a function onto it. The Haskell signature is : <code>(a -> b) -> F a -> F b</code>. The C++ implementation would be along the lines:</p>\n\n<pre><code>template <typename Fn, typename T>\nauto fmap(Fn fn, const Maybe<T>& mb) {\n\n using return_type = decltype(fn(std::declval<T>())); \n\n auto visitor = [fn](auto&& arg) -> Maybe<return_type> \n {\n using Type = std::decay_t<decltype(arg)>;\n if constexpr(std::is_same_v<Type, Nothing>) return Nothing();\n else return Just<return_type>(fn(arg.value));\n };\n\n return std::visit(visitor, mb); \n /* visit is the *apply* you're looking for: given a visitor with \n overloads for any type the variant can contain a value of, it \n will apply the correct overload on the value it contains */\n}\n</code></pre>\n\n<p>Now Maybe is also a monad. If you want to implement the <code>>>=</code> (aka <code>bind</code>), whose signature in Haskell is <code>(a -> M b) -> M a -> M b</code>, it isn't very different:</p>\n\n<pre><code>template <typename Fn, typename T>\nauto bind(Fn fn, const Maybe<T>& mb) {\n\n using return_type = decltype(fn(std::declval<T>())); \n\n auto visitor = [fn](auto&& arg) -> return_type \n {\n using Type = std::decay_t<decltype(arg)>;\n if constexpr(std::is_same_v<Type, Nothing>) return Nothing();\n else return fn(arg.value);\n };\n\n return std::visit(visitor, mb);\n}\n</code></pre>\n\n<p>Here's a <a href=\"https://wandbox.org/permlink/P3lXkzuKq6FQs58C\" rel=\"nofollow noreferrer\">link</a> to those few snippets of code if you feel like exploring that vein.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T16:54:04.640",
"Id": "211631",
"ParentId": "211558",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:14:27.740",
"Id": "211558",
"Score": "6",
"Tags": [
"c++",
"c++11",
"reinventing-the-wheel",
"optional"
],
"Title": "C++ Maybe<T> implementation"
} | 211558 |
<p>I've written a little piece of code to filter Firewall-Connection-Events by a certain group of IPs. But the code can't keep up since the input is fairly huge. I am looking for ways to make this code more efficient in order to handle the Firewall-Connection-Events.</p>
<p>[READ_CLIENTS]
The code starts with an empty list (client_IPs). The list is getting filled with unique IPs (read_clients), if the size of the file changes "read_clients" is called again to alter the list. </p>
<p>[READ_EVENTS]
To get the events, I've used While True to loop over the event-File and return the events with yield - if there is no new input, then sleep for 0.1 seconds.</p>
<p>[PROCESS_AND_FILTER]
After this I loop over the generator object to compare each event to each Unique-IP and seperate the result in two files.</p>
<pre><code> # -*- coding: utf-8 -*-
from IPy import IP
import os
import time
# Create String-Array to compare
path_unique_ips = '/var/log/unique.log'
# Sophos-UTM Packet-Accepted-Event | Connections to Customer-Net
path_sophos_to_customer = '/var/log/packet-accepted-sophos.log'
# match logs
match_log = '/var/log/matched.log'
no_match_log = '/var/log/not_matched.log'
# IP-Filter-Array
client_IPs = []
#get file size of unique ips file
size_ip_file = os.stat(path_unique_ips).st_size
def read_clients(path_unique_ips):
client_IPs_file = open(path_unique_ips, "r")
if client_IPs_file.mode == 'r':
# read all line from client_IPs_file
new_client_IPs = client_IPs_file.readlines()
#check for new clients and fill array
for new_client_IP in new_client_IPs:
if new_client_IP not in client_IPs:
client_IPs.append(IP(new_client_IP).strNormal())
def read_events(path_sophos_to_customer):
connection_event_to_customer = open(path_sophos_to_customer, 'r')
connection_event_to_customer.seek(0, 2)
if connection_event_to_customer.mode == 'r':
while True:
new_event = connection_event_to_customer.readline()
if not new_event:
time.sleep(0.1)
continue
yield new_event
#file size of unique IP File changed, re-run the function read_clients
if size_ip_file is not os.stat(path_unique_ips).st_size:
read_clients(path_unique_ips)
def process_and_filter(my_events):
#get events in generator-object from function read_events
# loop over generator-object, filled with events
for new_event in my_events:
print(new_event)
# loop over event with all ips
for client in client_IPs:
# if client-ip found in event write to match.log and break loop to go for next event
if client in new_event:
with open(match_log, 'a+') as matched:
matched.write(new_event)
break
# if ip wasn't in event write event to no_match.log
else:
with open(no_match_log, 'a+') as no_match:
no_match.write(new_event)
if __name__ == '__main__':
read_clients(path_unique_ips)
new_events=read_events(path_sophos_to_customer)
process_and_filter(new_events)
</code></pre>
<p><strong>Log_Event_Example</strong> :</p>
<blockquote>
<p>Jan 18 14:14:14 17.17.17.17 2019: 01:18-14:14:14 firewall-1
ulogd[5974]: id="2002" severity="info" sys="SecureNet"
sub="packetfilter" name="Packet accepted" action="accept" fwrule="653"
initf="eth1" outitf="eth0" srcmac="aa:bb:cc:dd:ee:ff"
dstmac="00:11:22:33:44:55" <strong>srcip="10.10.10.10"</strong> dstip="10.10.10.11"
proto="6" length="52" tos="0x00" prec="0x00" ttl="127" srcport="58589"
dstport="22" tcpflags="ACK"</p>
</blockquote>
| [] | [
{
"body": "<p>The main performance bottleneck is probably the fact that you keep your already seen IPs in a <code>list</code>. Doing <code>x in list</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, so the more IPs there are, the slower this will get. Another factor is that you check <code>if new_client_IP not in client_IPs</code> but then add <code>IP(new_client_IP).strNormal()</code> to the list. So even if you come across the same IP again, it will still not be in the list, since that class probably produces something different than the line (which will have a trailing newline, for example) (and if it does not produce anything different, why have this step at all?) and so you do this possibly expensive step again.</p>\n\n<p>Instead just save them in a <code>set</code>, for which <code>in</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. And even better, if you add an already existing element to a <code>set</code> it does not care.</p>\n\n<pre><code>client_IPs = set()\nclient_IPs_size = 0\n\ndef read_clients(path_unique_ips):\n \"\"\"Check if the file has changed size.\n If it has, extract all IPs from it and update the global variables.\n \"\"\"\n global client_IPs_size\n current size = os.stat(path_unique_ips).st_size\n if current_size != client_IPs_size:\n client_IPs_size = os.stat(path_unique_ips).st_size\n global client_IPs\n with open(path_unique_ips, \"r\") as client_IPs_file:\n client_IPs = {IP(line).strNormal() for line in client_IPs_file}\n</code></pre>\n\n<p>Note that I used <code>with</code> to ensure the file is properly closed, even in an event of an exception. I also used a <code>set</code> as stated above.</p>\n\n<p>I also iterate over the file directly instead of first reading all lines into memory. The whole thing fits nicely inside a set comprehension. I also added a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> to document what this function does.</p>\n\n<p>Modifying global objects can quickly lead to hard to read code and should be avoided if possible. Here this is a bit harder to avoid, because <code>process_and_filter</code> depends on the global state always being correct at that specific point in the loop. Another way around this would be to use class to keep this global state and make the other functions methods of that class. This might be a bit overkill, though, so I leave that implementation to you if you feel it is necessary.</p>\n\n<hr>\n\n<pre><code>def read_events(path_sophos_to_customer):\n \"\"\"Every 0.1 seconds check if a new non-blank line has been added to the end of the file.\n If there has, yield it.\n\n Read the file containing the list of IPs again if it has changed.\n \"\"\"\n with open(path_sophos_to_customer, 'r') as connection_event_to_customer:\n connection_event_to_customer.seek(0, 2) # seek to the end\n while True:\n new_event = connection_event_to_customer.readline()\n if not new_event:\n time.sleep(0.1)\n continue\n yield new_event\n\n # file size of unique IP File changed, this will read the IPs again\n read_clients(PATH_UNIQUE_IPS)\n</code></pre>\n\n<p>Since the check for a changed <code>client_IPs</code> is now inside <code>read_clients</code> the <code>if</code> clause is not needed anymore.</p>\n\n<p>I also removed the check if the file is readable. Usually you want your code to either fail loudly (with an exception) if something happens (like a file not being readable) or you catch that exception, do something about it and log that it happened. Having it just silently fail by bypassing it with that <code>if</code> clause does not help you at all.</p>\n\n<hr>\n\n<p>For the splitting of the events into two logs, I would open both files only once at the beginning. I would also extract the IP from the event (since you have not shown us an example of what an event looks like, I will have to guess and say you could use for example <a href=\"https://www.regular-expressions.info/ip.html\" rel=\"nofollow noreferrer\"><code>re.search(r'\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b', new_event).group()</code></a>). This moves this from having to iterate over all IPs every time to iterating over the string of <code>new_event</code>, which is hopefully shorter.</p>\n\n<pre><code>def process_and_filter(my_events, match_log, no_match_log):\n \"\"\"Get events in generator-object from function read_events\n and write either to matched or no match log file.\n \"\"\"\n with open(match_log, 'a+') as match, open(no_match_log, 'a+') as no_match:\n for new_event in my_events:\n print(new_event)\n ip = extract_ip(new_event)\n file = match if ip in client_IPs else no_match\n file.write(new_event)\n</code></pre>\n\n<hr>\n\n<p>With this the calling code becomes:</p>\n\n<pre><code>if __name__ == '__main__':\n new_events = read_events(PATH_SOPHOS_TO_CUSTOMER, MATCH_LOG, NO_MATCH_LOG)\n process_and_filter(new_events)\n</code></pre>\n\n<p>Note that Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, recommends using <code>ALL_CAPS</code> for global constants.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T10:44:50.510",
"Id": "409476",
"Score": "0",
"body": "Thanks alot correcting my code - I'll test it asap ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T10:51:53.310",
"Id": "409477",
"Score": "0",
"body": "One question - \n[BEFORE]:\ncheck if file_size of unique.log has changed . if so, call read_clients - \n[AFTER]: \ncall read_clients to check if file_size of unique.log has changed. wasn't it faster before, since the function wasnt called all the time ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T11:34:58.000",
"Id": "409479",
"Score": "0",
"body": "@peacemaker: Calling the function does not have a very high overhead (but it does have some). But I'm pretty sure the disk access to check the file size dominates that. If it is an issue (and you should find out if it is a bottleneck via timing) you can always move it back there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T14:57:50.663",
"Id": "409500",
"Score": "0",
"body": "I changed the script as you recommended and it works out just fine . Thanks for your help."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:07:26.183",
"Id": "211689",
"ParentId": "211559",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211689",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:49:39.847",
"Id": "211559",
"Score": "1",
"Tags": [
"python",
"performance",
"python-2.x"
],
"Title": "Python Firewall-Connection-Event Filter too slow"
} | 211559 |
<p><a href="https://codereview.stackexchange.com/q/211366/183642">Here</a> I asked this question:</p>
<blockquote>
<p>My goal is to go through the <a href="https://github.com/dwyl/english-words" rel="nofollow noreferrer">list of all English words</a> (separated by
<code>'\n'</code> characters) and find the longest word which doesn't have any of
these characters: "gkmqvwxz". And I want to optimize it as much as
possible</p>
</blockquote>
<p>I updated the code with the help of suggestions from answers, but I still need comments on this updated version</p>
<p>Changes:</p>
<ol>
<li>Name of the file and the forbidden characters are no longer hard-coded. They are passed by arguments.</li>
<li>Added several error checks.</li>
<li>Used pointers instead of indexes.</li>
<li><code>buffer</code> is freed when we're done with it.</li>
<li>Used <code>bool</code> instead of <code>int</code> for the return type of <code>is_legal</code>.</li>
<li>Parameters to <code>is_legal</code> are made <code>const</code> since we don't change them.</li>
<li>Skip next lines (<code>'\n'</code>) remaining from previous lines.</li>
<li>Added some functions to keep main simple.</li>
<li>Removed superfluous headers (<code>#include <string.h></code>, <code>#include <stddef.h></code>, <code>#include <unistd.h></code>).</li>
<li><code>is_legal</code> need not know about the entire <code>buffer</code>. Just the relevant pointers are now sent.</li>
<li><code>length</code> is no longer fixed. We get the size of the array at runtime</li>
<li><code>buffer</code> is terminated with null. </li>
</ol>
<p>Updated code: </p>
<pre><code>#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
static inline bool is_legal(const char* beg, size_t size, const char* bad)
{
for (; size-- !=0 ; ++beg) { /* go through current word */
char ch = tolower(*beg); /* The char might be upper case */
for (const char* bad_ptr = bad; *bad_ptr; ++bad_ptr)
if (ch == *bad_ptr) /* If it is found, return false */
return false;
}
return true; /* else return true */
}
static inline size_t get_next_word_size(const char* beg)
{
size_t size = 0; /* resulting size */
for (; beg[size] && beg[size] != '\n'; ++size) /* read the next word */
{ } /* for loop doesn't have a body */
return size;
}
static inline char* get_buffer(const char* filename)
{
char *buffer = NULL; /* contents of the text file */
size_t length; /* maximum size */
FILE* fp;
fp = fopen(filename, "rb");
if (!fp) { /* checking if file is properly opened */
perror("Couldn't open the file\n");
return NULL;
}
if (fseek(fp, 0, SEEK_END)) {
perror("Failed reading");
return NULL;
}
length = ftell(fp);
if (fseek(fp, 0, SEEK_SET)) {
perror("Failed reading");
return NULL;
}
buffer = malloc(length + 1); /* +1 for null terminator */
if (buffer == NULL) { /* checking if memory is allocated properly */
perror("Failed to allocate memory\n");
free(buffer);
return NULL;
}
fread(buffer, 1, length, fp); /* read it all */
fclose(fp);
buffer[length] = '\0'; /* terminate the string with null*/
return buffer;
}
int main(int argc, char **argv)
{
if (argc < 3) {
printf("Usage: FileName BadChars");
return 0;
}
char* filename = argv[1];
char* badchars = argv[2];
char *buffer = get_buffer(filename);
if (buffer == NULL) {
return -1;
}
const char *beg = buffer; /* current word boundaries */
size_t size = 0;
const char *mbeg = beg; /* result word */
size_t msize = 0;
while (beg[size]) {
beg += size + 1; /* +1 to skip the '\n' */
size = get_next_word_size(beg); /* get the size of the next word */
if (size > msize && is_legal(beg, size, badchars)) { /* if it is a fit, save it */
mbeg = beg;
msize = size;
}
}
printf("%.*s\n", msize, mbeg); /* print the output */
free(buffer);
return 0;
}
</code></pre>
<p>I would especially appreciate comments regarding the way the code reads the entire file into a single dynamically allocated array. About if and how it could be improved. I wouldn't like to sacrifice the performance, but some "best practices" especially about this part are very welcome.</p>
| [] | [
{
"body": "<p><strong>Questionable Design</strong> </p>\n\n<p>The idea to read in the <em>entire</em> file and then process it has weaknesses:</p>\n\n<ol>\n<li><p>Code can only handle files fit-able in memory. Risks allocation failures.</p></li>\n<li><p>Limitations with file sizes more than <code>SIZE_MAX</code> and <code>LONG_MAX</code>.</p></li>\n</ol>\n\n<p>Code could read in 1 \"word\" at a time. </p>\n\n<p>If performance is an issue, then read in perhaps a block of memory at a time.</p>\n\n<p><strong>Expand uses</strong></p>\n\n<p>Consider if <code>argc == 2</code>, then with a stream view of the file as suggested above, <code>stdin</code> could be used as the input. This makes for a useful \"pipe-able\" tool.</p>\n\n<pre><code>foo | Ayxan_filter \"gkmqvwxz\"\n</code></pre>\n\n<p><strong>Certainly a bug on first word</strong> </p>\n\n<p>Code's first call to <code>get_next_word_size()</code> is <code>get_next_word_size(1)</code>, I'd expect <code>get_next_word_size(0)</code></p>\n\n<p>Perform a <code>size++</code> at the end of the loop rather than a <code>+ 1</code> at the beginning.</p>\n\n<p><strong>Wrong type</strong></p>\n\n<p>Precision specifier should be <code>int</code>, else code is UB.</p>\n\n<pre><code>// printf(\"%.*s\\n\", msize, mbeg);\nprintf(\"%.*s\\n\", (int) msize, mbeg);\n</code></pre>\n\n<p>We can assume <code>msize <= INT_MAX</code> too, but pedantic code would check that first.</p>\n\n<p><strong>Questionable processing with binary mode</strong></p>\n\n<p>File is opened in binary mode <code>\"rb\"</code> yet looks for <code>'\\n'</code> as end-of-line. I can foresee trouble with text files that end lines with <code>\"\\r\\n\"</code> or the rare <code>\"\\r\"</code>.</p>\n\n<p>For me, to be highly portable, I would still open in binary mode but use the presence of <code>'\\n'</code> or <code>'\\r'</code> as an end-of-line.</p>\n\n<p><strong>Code can quit early</strong></p>\n\n<p>Should the file contain a <em>null character</em>, its presence will stop the search early. </p>\n\n<p>Robust could would not treat the file as a <em>string</em>, but as a character array.</p>\n\n<p><strong>Resource leak</strong></p>\n\n<p><code>fclose(fp);</code> missing from various error returns from <code>get_buffer()</code>.</p>\n\n<p><strong><code>islower()</code></strong></p>\n\n<p><code>islower(int ch)</code> is defined for values in the <code>unsigned char</code> range and <code>EOF</code>. Calling it with a <code>char</code> can lead to undefined behavior with a negative value.</p>\n\n<pre><code>// char ch = tolower(*beg); \nchar ch = tolower((unsigned char) *beg); \n</code></pre>\n\n<p><strong><code>is_legal()</code> alternative</strong></p>\n\n<pre><code>// No need for size, but append '\\n' to the `bad` before this call.\nstatic inline bool is_legal(const char* beg, /* size_t size, */ const char* bad) {\n char *y = strcspn(beg, bad);\n if (y == NULL) return true;\n return *y == '\\n';\n}\n</code></pre>\n\n<h2>Strongly recommend:</h2>\n\n<p>To really move things along, rather than search each character to see it it is in a list of bad ones, create a table (I'd do all using <code>unsigned char</code>) This is reasonable as long as <code>UCHAR_MAX</code> is a sane a value. I suspect this will measurable improve performance.</p>\n\n<pre><code>bool bad_boys[UCHAR_MAX+1];\nfoo_populate(bad_boys, bad);\n\n// Insure '\\0', '\\n' are true.\nstatic inline bool is_legal_alt2(const char* beg, const bool *bad_boys) {\n const unsigned char* ubeg = (const unsigned char*) beg;\n while (!bad_boys[*ubeg]) {\n ubeg++;\n }\n return *ubeg == '\\n' || ubeg == '\\0';\n}\n</code></pre>\n\n<p><strong>Code assumes <code>size_t</code> is like <code>long</code></strong></p>\n\n<p>The length returned is a <code>long</code>. Its range may be more or less than <code>size_t</code>. Better code would not assume either.</p>\n\n<pre><code>//size_t length;\n//length = ftell(fp);\nsize_t length;\nlong ilength = ftell(fp);\n\n#if LONG_MAX >= SIZE_MAX\n// >= used here rather than > due to later +1 in the allocation\nif (ilength >= SIZE_MAX) {\n perror(\"Too big\\n\");\n return NULL; \n} \n#endif\n\n// Unclear what risks you want to take here.\n// Suggest to just bail out\nif (ilength < 0) {\n perror(\"Unclear size\\n\");\n return NULL; \n}\n\nlength = (size_t) ilength;\n</code></pre>\n\n<p><strong>No check for <code>ftell()</code>, <code>fread()</code> error</strong></p>\n\n<p>An error here is critical and not so improbable.</p>\n\n<pre><code>ilength = ftell(fp);\n// add\nif (ilength == -1) {\n perror(\"ftell error\\n\");\n return NULL; \n}\n\n//fread(buffer, 1, length, fp); \nif (fread(buffer, 1, length, fp) != length) {\n perror(\"fread error\\n\");\n return NULL; \n}\n</code></pre>\n\n<p><strong>Questionable style</strong></p>\n\n<p>Consider a <code>while</code> loop</p>\n\n<pre><code>//for (; beg[size] && beg[size] != '\\n'; ++size) /* read the next word */\n//{ } /* for loop doesn't have a body */\n\nwhile (beg[size] && beg[size] != '\\n') {\n ++size;\n}\n</code></pre>\n\n<p><strong>Unneeded <code>free()</code></strong></p>\n\n<p>No need for call <code>free(NULL)</code>;</p>\n\n<pre><code> if (buffer == NULL) {\n perror(\"Failed to allocate memory\\n\");\n// free(buffer); // not needed\n return NULL;\n}\n</code></pre>\n\n<p><strong>Consider sentinels</strong></p>\n\n<p>A \"word\" may have leading/trailing spaces. In a pathological case, the longest word will be <code>\"\"</code>. Consider sentinels characters to show clearly the word.</p>\n\n<pre><code>//printf(\"%.*s\\n\", msize, mbeg);\nprintf(\"\\\"%.*s\\\"\\n\", msize, mbeg);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:17:32.783",
"Id": "211580",
"ParentId": "211560",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "211580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T16:16:13.183",
"Id": "211560",
"Score": "2",
"Tags": [
"performance",
"c",
"strings",
"file"
],
"Title": "Finding the longest word without these characters follow-up"
} | 211560 |
<p>This is an implementation to simulate the basic functionality of <code>unique_ptr</code>.<br>
This doesn't provide features like custom deleter and <code>make_unique()</code>.</p>
<p>I would really appreciate any feedback to improve the below code, any other api's that I should be providing etc.</p>
<p><strong>my_unique_ptr.h</strong></p>
<pre><code>#ifndef MY_UNIQUE_PTR_H_
#define MY_UNIQUE_PTR_H_
#include <utility>
namespace kapil {
template <typename T>
class unique_ptr final {
private:
T* ptr_;
unique_ptr(const unique_ptr&) = delete; // Make unique_ptr non copy constructible
unique_ptr& operator = (const unique_ptr&) = delete; // Make unique_ptr non copy assignable
public:
explicit unique_ptr (T* ptr = nullptr) noexcept
: ptr_{ptr} { }
unique_ptr(unique_ptr<T>&& rval) noexcept // Move constructor
: ptr_{rval.ptr_} {
rval.ptr_ = nullptr;
}
unique_ptr& operator = (unique_ptr&& rhs) noexcept { // Move assignment
delete ptr_;
ptr_ = rhs.ptr_;
rhs.ptr_ = nullptr;
return *this;
}
~unique_ptr() noexcept {
delete ptr_;
}
T* release() noexcept {
T* old_ptr = ptr_;
ptr_ = nullptr;
return old_ptr;
}
void reset(T* ptr = nullptr) noexcept {
delete ptr_;
ptr_ = ptr;
}
void swap(unique_ptr& rhs) noexcept {
std::swap(ptr_, rhs.ptr_);
}
T* get() const noexcept {
return ptr_;
}
explicit operator bool() const noexcept {
return (ptr_ != nullptr);
}
T& operator * () const {
return *ptr_;
}
T* operator -> () const noexcept {
return ptr_;
}
friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
return lhs.get() == rhs.get();
}
friend bool operator != (const unique_ptr& lhs, const unique_ptr& rhs) {
return !(lhs == rhs);
}
};
template <typename T>
void swap(unique_ptr<T>& lhs, unique_ptr<T>& rhs) {
lhs.swap(rhs);
}
} //kapil
#endif
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Don't mark your class <code>final</code> without a good reason. It inhibits user-freedom.</p></li>\n<li><p>The default-access for members of a <code>class</code> is already <code>private</code>.</p></li>\n<li><p>Explicitly deleting <a href=\"https://en.cppreference.com/w/cpp/language/copy_constructor\" rel=\"nofollow noreferrer\">copy-constructor</a> and <a href=\"https://en.cppreference.com/w/cpp/language/copy_assignment\" rel=\"nofollow noreferrer\">copy-assignment-operator</a> is superfluous, as you define move-constructor and move-assignment, which <em>already</em> suppresses them. Still, some assert being explicit adds clarity.</p></li>\n<li><p>I wonder why you didn't declare construction from <code>T*</code> to be <code>constexpr</code>...</p></li>\n<li><p>Try to consistently use the injected class-name (<code>unique_ptr</code>), instead of sporadically naming the template-arguments (<code>unique_ptr<T></code>).</p></li>\n<li><p>You are missing implicit upcasting in the move-ctor and move-assignment-operator.</p>\n\n<pre><code>template <class U, class = std::enable_if_t<\n std::has_virtual_destructor<T>() && std::is_convertible<U*, T*>()>>\nunique_ptr(unique_ptr<U>&& other) noexcept\n: ptr_(other.release())\n{}\n\ntemplate <class U>\nauto operator=(std::unique_ptr<U>&& other) noexcept\n-> decltype((*this = unique_ptr(other))) {\n return *this = unique_ptr(other);\n}\n</code></pre></li>\n<li><p>Take a look at <a href=\"https://en.cppreference.com/w/cpp/utility/exchange\" rel=\"nofollow noreferrer\"><code>std::exchange(object, value)</code> from <code><utility></code></a>. It allows you to simplify some of your code.</p></li>\n<li><p>If you use move-and-swap, you could isolate freeing of the referee to the dtor. Having it at only one place ensures you always do it the same, and is a good first step for retrofitting custom deleters. Not to mention that it in many cases simplifies the implementation.</p></li>\n<li><p><code>(ptr != nullptr)</code> can be simplified to <code>ptr</code>. In contexts where you have to force the type, <code>!!ptr</code>.</p></li>\n<li><p>Why are <code>op==()</code> and <code>op!=()</code> inline-friend-functions, but <code>swap()</code> isn't? That's inconsistent. It's especially puzzling as they are all written to use the public interface only.</p></li>\n<li><p>There is exactly one place where you don't have a single empty line between two functions, but two. Yes, that's nothing big.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:24:10.930",
"Id": "211574",
"ParentId": "211565",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "211574",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:00:22.773",
"Id": "211565",
"Score": "7",
"Tags": [
"c++",
"c++11",
"reinventing-the-wheel",
"pointers"
],
"Title": "unique_ptr basic implementation for single objects"
} | 211565 |
<p>I created a basic Hangman game that uses a text file to select a secret word. Are there any areas for improvement?</p>
<pre><code>import random
secret_word = ['']
user_list = []
number_of_tries = 5
guessed_letters = []
user_tries = 0
user_guess = ''
def select_word():
global secret_word, user_list
with open('secret_words.txt', 'r') as f:
word = f.read()
word_list = word.split('\n')
secret_word = word_list[random.randint(1, len(word_list))]
user_list = ['-'] * len(secret_word)
def game_over():
if user_tries == number_of_tries or user_list == list(secret_word):
return True
else:
return False
def user_input():
global user_guess
user_guess = input('Guess a letter\n')
check_guess(user_guess)
def repeated(guess):
global guessed_letters
if guess in guessed_letters:
print('You already guessed that letter!\n')
return True
else:
guessed_letters.append(user_guess)
return False
def check_guess(guess):
correct_guess = False
for x in range(len(secret_word)):
if guess == secret_word[x]:
user_list[x] = guess
correct_guess = True
elif not correct_guess and x == len(secret_word)-1:
global user_tries
user_tries += 1
print('Wrong guess, you lose one try\n'
'Remaining tries : {}\n'.format(number_of_tries - user_tries))
if correct_guess:
print('Correct guess!')
def valid_input(user_letter):
valid_letters = 'qwertyuiopasdfghjklzxcvbnm'
if user_letter.lower() in list(valid_letters):
return True
else:
print('Invalid input')
return False
# main code:
print('----HANG MAN----')
print('*Welcome, guess the word\n*you have 5 tries.')
select_word()
while not game_over():
for x in user_list:
print(x, end='')
user_guess = input('\nGuess a letter : ')
if valid_input(user_guess):
if repeated(user_guess):
continue
else:
check_guess(user_guess)
if user_list != list(secret_word):
print('Game over, you died!\ncorrect word was {}'.format(secret_word))
else:
print('Congratulations! you guessed the correct word\n')
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>this if statement is a bit silly:</p>\n\n<pre><code> if user_tries == number_of_tries or user_list == list(secret_word):\n return True\n else:\n return False\n</code></pre>\n\n<p>It could easily be:</p>\n\n<pre><code> return user_tries == number_of_tries or user_list == list(secret_word)\n</code></pre>\n\n<p>since that expression evaluates to <code>True</code> or <code>False</code>, just return it directly</p></li>\n<li><p>Instead of</p>\n\n<pre><code>secret_word = word_list[random.randint(1, len(word_list))]\n</code></pre>\n\n<p>you can use the much more readable <code>random.choice</code>:</p>\n\n<pre><code>secret_word = random.choice(word_list)\n</code></pre></li>\n<li><p>your <code>user_input</code> routine isn't used at all. Nuke it or use it.</p></li>\n<li><p>You use a lot of global state. This is generally frowned upon because it makes the code less reusable. You should first off, try to use less global state: put function results into variables and pass them around, instead. This makes those functions much more reusable. If you absolute <em>must</em> use global state, <em>still</em> don't: instead make an object that stores that \"global\" state, and turn the functions that use it into methods on the object. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T20:35:38.537",
"Id": "409540",
"Score": "0",
"body": "Thank you for useful comment.\nCan you explain more about passing variables around"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T03:00:05.880",
"Id": "211592",
"ParentId": "211567",
"Score": "6"
}
},
{
"body": "<p>For the word selection, there is a bug on </p>\n\n<p><code>secret_word = word_list[random.randint(1, len(word_list))]</code></p>\n\n<p>you should change to</p>\n\n<p><code>secret_word = word_list[random.randint(0, len(word_list)-1)]</code></p>\n\n<p>because <code>random.randint(1, len(word_list))</code> does not return <code>0</code> index, and could return an index off the bound (<code>len(word_list)</code>).</p>\n\n<p>Also, you may remove <code>secret_word = ['']</code> and <code>user_list=[]</code> at the beginning.</p>\n\n<pre><code>number_of_tries = 5\nguessed_letters = []\nuser_tries = 0\nuser_guess = ''\n\ndef select_word():\n with open('secret_words.txt', 'r') as f:\n word = f.read()\n word_list = word.split('\\n')\n secret_word = word_list[random.randint(0, len(word_list)-1)]\n user_list = ['-'] * len(secret_word)\n return secret_word, user_list\n</code></pre>\n\n<p>looks more compact. So you can use it as :</p>\n\n<pre><code>print('----HANG MAN----')\nprint('*Welcome, guess the word\\n*you have 5 tries.')\n\nsecret_word, user_list = select_word()\n\n...\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>Also for efficiency and compactness, you can change this</p>\n\n<pre><code>while not game_over():\n for x in user_list:\n print(x, end='')\n user_guess = input('\\nGuess a letter : ')\n if valid_input(user_guess):\n if repeated(user_guess):\n continue\n else:\n check_guess(user_guess)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>while not game_over():\n print(''.join(user_list))\n user_guess = input('\\nGuess a letter : ')\n if valid_input(user_guess):\n if not repeated(user_guess):\n check_guess(user_guess)\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>For the game itself, you may want to try using classes, which will make it more readable and easier to analyze.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T20:39:10.667",
"Id": "409541",
"Score": "1",
"body": "Thank you, I think you explained pjz suggestion of passing variables around instead of using global? will use that looks much better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T00:09:45.160",
"Id": "409559",
"Score": "1",
"body": "As pjz said : \"put function results into variables and pass them around,\" is like what I did the `select_word` function..we can just move the global variables to become variables with values from results of the function"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T04:44:19.087",
"Id": "211659",
"ParentId": "211567",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211659",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:38:56.410",
"Id": "211567",
"Score": "3",
"Tags": [
"python",
"beginner",
"game",
"hangman"
],
"Title": "Simple Hangman game - first Python project"
} | 211567 |
<p>This code is for a board game program, which works by placing the user on a grid which then tasks the user with finding all the treasure chests. Each chest landed on gives 10 gold. However, landing on a bandit means all your gold is taken. There are also different difficulties. The end score is then given once the user has found all the chests. I have managed to added features such as a leaderboard, save system, and tkinter has been implemented.</p>
<p>I want any advice on how to make the code more efficient, presentable or user-friendly. I do also wish to add an SQL database soon as I do want to add the gameplay feature of the program asking a question to the user whenever they land on a chest. Should the user answer correctly, they get the gold in the chest.</p>
<pre><code>from tkinter import ttk
from tkinter import messagebox
import tkinter
import random
import sys
import time
import os
import pickle #module used to serielize objects
import json
from playsound import playsound
window = tkinter.Tk()
window.title("")
boardeasy=[]
boardmed=[]
boardhard=[]
current=[0,0]
treasures = [(random.randint(0,8), random.randint(0,8)) for i in range(12)]
bandits = [(random.randint(0,8), random.randint(0,8)) for i in range(12)]
Coins = 0
Chest = 10
Bandit1 = 5
Bandit2 = 7
Bandit3 = 10
class user():
def __init__(self, username, userscore, usertime):
self.username = username
self.userscore = userscore
self.usertime = usertime
#For loop prints a new 8*8 grid after every move
boardeasy = [[' ' for j in range(8)] for i in range(8)]
def table_game_easy():
print(" 1 2 3 4 5 6 7 8")
print("---------------------------------")
for row in range(8):
print ('| ' + ' | '.join(boardeasy[row][:8]) + ' | ' + str(row + 1))
print("---------------------------------")
treasures_row = [random.randint(0,8) for i in range(10)]
treasures_col = [random.randint(0,8) for i in range(10)]
bandits_row = [random.randint(0,8) for i in range(5)]
bandits_col = [random.randint(0,8) for i in range(5)]
# For loop prints a new 10*10 grid after every move
boardmed = [[' ' for j in range(10)] for i in range(10)]
def table_game_meduim():
print(" 1 2 3 4 5 6 7 8 9 10")
print("------------------------------------------")
for row in range(10):
print ('| ' + ' | '.join(boardmed[row][:10]) + ' | ' + str(row + 1))
print("------------------------------------------")
treasures_row = [random.randint(0,10) for i in range(10)]
treasures_col = [random.randint(0,10) for i in range(10)]
bandits_row = [random.randint(0,10) for i in range(7)]
bandits_col = [random.randint(0,10) for i in range(7)]
# For loop prints a new 12*12 grid after every move
boardhard = [[' ' for j in range(12)] for i in range(12)]
def table_game_hard():
print(" 1 2 3 4 5 6 7 8 9 10 11 12")
print("----------------------------------------------------")
for row in range(12):
print ('| ' + ' | '.join(boardhard[row][:12]) + ' | ' + str(row + 1))
print("----------------------------------------------------")
treasures_row = [random.randint(0,10) for i in range(10)]
treasures_col = [random.randint(0,10) for i in range(10)]
bandits_row = [random.randint(0,10) for i in range(10)]
bandits_col = [random.randint(0,10) for i in range(10)]
#this function is in charge of downwards movement
def down(num,lev):
num=(num+current[0])%lev#The % formats this equation
current[0]=num
#this function is in charge of downwards movement
def right(num,lev):
num=(num+current[1])%lev #The % formats this equation
current[1]=num
#this function is in charge of downwards movement
def left(num,lev):
if current[1]-num>=0:
current[1]=current[1]-num
else:
current[1]=current[1]-num+lev
#this function is in charge of downwards movement
def up(num,lev):
if current[0]-num>=0:
current[0]=current[0]-num
else:
current[0]=current[0]-num+lev
def easy_level(Coins, Chest, Bandit1):
playsound('audio.mp3', block = False)
#This function is for the movement of the game in easy difficulty
p = 0
while True and Chest > 0:
p = p+1
if p == 5:
print("Do you want to save the game?")
choice = input(">")
if choice == 'yes':
with open('file.txt', 'w') as f:
json.dump([Coins, Chest, Bandit1], f)
oldcurrent=current
boardeasy[oldcurrent[0]][oldcurrent[1]]='*'
table_game_easy()
boardeasy[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 8 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:#Validates input
print('Wrong command, please input again')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),8)#Boundary is set to 8 as the 'easy' grid is a 8^8
elif n[0].lower()=='down':
down(int(n[1].lower()),8)
elif n[0].lower()=='left':
left(int(n[1].lower()),8)
elif n[0].lower()=='right':
right(int(n[1].lower()),8)
print(Chest,"chests left")
print(Bandit1,"bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if (current[0], current[1]) in treasures[:8]:
Chest = Chest - 1
print("Hooray! You have found booty! +10 gold")
Coins = Coins + 10 #Adds an additional 10 points
print("Coins:",Coins)
if (current[0], current[1]) in bandits[:8]:
Bandit1 = Bandit1 - 1
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardeasy[current[0]][current[1]]='*'#sets value to players position
#Label box
labelOne = ttk.Label(window, text = "Enter your username:")
labelOne.grid(row = 0, column = 0)
#Userinput is set to variable
UserName = tkinter.StringVar()
#Input box
userEntry = ttk.Entry(window, width = 26, textvariable = UserName)
userEntry.grid(row = 0, column = 1)
def action():
username1 = UserName.get()
with open("high_scores.txt","a") as f:
f.write(str(Coins)+ os.linesep)
f.write(username1 + os.linesep)
f.close()
window.destroy()
btn = ttk.Button(window, text = "Submit", command = action)
btn.grid(row = 0, column = 2)
window.mainloop()
def med_level(Coins, Chest, Bandit2):
playsound('audio.mp3', block = False)
#This function is for the movement of the game in medium difficulty
while True:
oldcurrent=current
boardmed[oldcurrent[0]][oldcurrent[1]]='*'
table_game_meduim()
boardmed[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 10 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:
print('wrong command')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),10)#Boundary is set to 10 as the 'easy' grid is a 10^10
elif n[0].lower()=='down':
down(int(n[1].lower()),10)
elif n[0].lower()=='left':
left(int(n[1].lower()),10)
elif n[0].lower()=='right':
right(int(n[1].lower()),10)
print(Chest,"chests left")
print(Bandit2,"bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if (current[0], current[1]) in treasures[:10]:
Chest = Chest - 1
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if (current[0], current[1]) in bandits[:10]:
Bandit2 = Bandit2 - 1
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardmed[current[0]][current[1]]='*'
def hard_level(Coins, Chest, Bandit3):
playsound('audio.mp3', block = False)
#This function is for the movement of the game in hard difficulty
while True:
oldcurrent=current
boardhard[oldcurrent[0]][oldcurrent[1]]='*'
table_game_hard()
boardhard[oldcurrent[0]][oldcurrent[1]]=' '
n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 12 \n')
n=n.split()
if n[0].lower() not in ['up','left','down','right']:
print('wrong command')
continue
elif n[0].lower()=='up':
up(int(n[1].lower()),12)#Boundary is set to 12 as the 'hard' grid is a 12^12
elif n[0].lower()=='down':
down(int(n[1].lower()),12)
elif n[0].lower()=='left':
left(int(n[1].lower()),12)
elif n[0].lower()=='right':
right(int(n[1].lower()),12)
print(Chest,"chests left")
print(Bandit3,"bandits left")
print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
if (current[0], current[1]) in treasures[:12]:
Chest = Chest - 1
print("Hooray! You have found booty! +10 gold")
Coins = Coins+10 #Adds an additional 10 points
print("Coins:",Coins)
if (current[0], current[1]) in bandits[:12]:
Bandit2 = Bandit2 - 1
print("Oh no! You have landed on a bandit...they steal all your coins!")
Coins = Coins-Coins #Removes all coins
print("Coins:",Coins)
boardhard[current[0]][current[1]]='*'
def instruct():
difficulty = input("""Before the game starts, please consider what difficulty
would you like to play in, easy, medium or (if you're brave) hard.
""")
if difficulty == "easy":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
time.sleep(1)
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
easy_level(Coins, Chest, Bandit1)
elif difficulty == "medium":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
time.sleep(1)
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
med_level(Coins, Chest, Bandit2)
elif difficulty == "hard":
print("That's great! Lets continue.")
time.sleep(1)#Allows the user time to get ready
print("initiating game in...")
time.sleep(1)
print()
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
for i in range(3):
print("")
hard_level(Coins, Chest, Bandit3)
else:
print("Sorry, that is an invalid answer. Please restart the programme")
def menu():
#This function lets the user quit the application or progress to playing.
print("")
print ("Are you sure you wish to play this game? Please answer either yes or no.")
choice1 = input() # Sets variable to user input
if choice1.lower().startswith('y'):
print("Okay lets continue then!")
print("")
print("")
print("""~~~~~~~~~~MENU~~~~~~~~~~
1). Load a previous game
2). Display the high score table
3). Continue
""")
choice2 = input(">")
while choice2 != '3':
print("")
print("")
print("""~~~~~~~~~~MENU~~~~~~~~~~
1). Load a previous game
2). Display the high score table
3). Continue
""")
choice2 = input(">")
if choice2 == "1":
with open('file.txt') as f:
coins, chests, bandits = json.load(f)
elif choice2 == "2":
with open("high_scores.txt") as f:
for line in f:
print(line)
print("")
elif choice1.lower().startswith('n'):
print("Thank you, I hope you will play next time!")
print("")
quit("Thank you for playing!")#Terminates the programme
else:
print("Sorry, that is an invalid answer. Please restart the programme")
print("")
quit()
instruct()
def showInstructions():
#hides main window
window.withdraw()
#message box display
messagebox.showinfo("Instructions","""You are a treasure hunter, your goal is to collect atleast 100 gold by the end
of the game from treasure chests randomly scattered across the grid. There are
10 chests within a grid (this can be changed based on difficulty) and each
treasure chest is worth 10 gold but can only be reclaimed 3 times before it is
replaced by a bandit. Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then
100 gold this means you lose!
Press enter to continue...""")
messagebox.showinfo("Instructions","""At the start of the game, you always begin at the top right of the grid.
Below is a representation of the game:
* 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Press enter to continue...""")
messagebox.showinfo("Instructions","""When deciding where to move, you should input the direct co-ordinates of your
desired location. For instance:
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
right 3
0 0 0 * 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Unlucky move! You have found nothing!
If nothing on the grid changes , this means that your move was a bust! Landing
on nothing isn't displayed on the grid.
Press enter to continue...""")
messagebox.showinfo("Instructions","""
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
down 4
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Hooray! You have found booty! +10 gold
Here you can see that the use has landed on a chest!
As you land on chest, they get replaced by bandits. Be sure to remember the
previous locations so you don't accidently land on a bandit and lose all
your gold!
Press enter to continue...""")
#Introduces the user
print('Welcome to the Treasure hunt!')
time.sleep(0.3)
print()
time.sleep(0.3)
print('Would you like to see the instructions? (yes/no)')
if input().lower().startswith('y'):#If function checks for the first letter
showInstructions()
elif input == 'no' or 'No':
print("Lets continue then!")#Calls the function which displays instructions
else:
print("Please check your input and try again.")
menu()
</code></pre>
| [] | [
{
"body": "<p>Minor notes:</p>\n\n<ul>\n<li><p>this:</p>\n\n<pre><code>boardeasy = [[' ' for j in range(8)] for i in range(8)]\n</code></pre>\n\n<p>can skip the loops and be:</p>\n\n<pre><code>boardeasy = [ [ ' ' ] * 8 ] * 8 ]\n</code></pre></li>\n<li><p>Instead of <code>table_game_easy</code>, <code>table_game_medium</code> and <code>table_game_hard</code> that print out boards stored in global variables, make a generic <code>print_board</code> routine, and also make a more general routine <code>table_game(size)</code> that can generate a square board of any size. Then your 'easy', 'medium' and 'hard' can be just calls to set <code>board = table_game(size)</code> where size is 8, 10, or 12 depending on the difficulty.</p></li>\n<li><p>code like</p>\n\n<pre><code>current[1]=current[1]-num\n</code></pre>\n\n<p>should be written like:</p>\n\n<pre><code>current[1] -= num\n</code></pre>\n\n<p>as it's both shorter and less error-prone</p></li>\n<li><p>this</p>\n\n<pre><code>while True and Chest > 0:\n</code></pre>\n\n<p>is the exact same as:</p>\n\n<pre><code>while Chest > 0:\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:10:06.977",
"Id": "409133",
"Score": "2",
"body": "Your first bullet point is bad advice as now `boardeasy[0]` is the same object as `boardeasy[1]` and so on. So setting `boardeasy[x][y]` does __not__ have the expected effect but instead set 8 cells at a time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T02:44:42.160",
"Id": "211591",
"ParentId": "211571",
"Score": "0"
}
},
{
"body": "<ol>\n<li><p>Move your startup/init code into a <code>main</code> routine, and replace it with the more usual Python idiom:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre></li>\n<li><p>As a pet peeve, get rid of the delay timers. I don't think they add any value, and they do make it irritating when debugging.</p></li>\n<li><p>Move your data away from your code. For example, you have a bunch of literal text in your <code>showInstructions</code> function. Instead, create a list of tuples:</p>\n\n<pre><code>INSTRUCTIONS = [ # (title, text)\n (\"Instructions\", \"\"\"You are a treasure hunter, your goal is to collect at least \n 100 gold by the end of the game from treasure chests randomly ...\"\"\"),\n # ... etc ...\n]\n</code></pre>\n\n<p>Then use the tuples in a simple loop inside <code>showInstructions</code>:</p>\n\n<pre><code>def showInstructions():\n \"\"\"Hide main window, then show a series of message boxes with instructions in them.\"\"\"\n\n window.withdraw()\n for title, text in INSTRUCTIONS:\n messageBox(title, text)\n</code></pre>\n\n<p>Also, since your message boxes always end with \"Press enter to continue...\" go ahead and define a <code>messageBox</code> function that appends that text.</p>\n\n<pre><code>def messageBox(title, text):\n message = text.rstrip() + '\\n\\nPress enter to continue...'\n messagebox.showinfo(title, message)\n</code></pre></li>\n<li><p>Decide how you want to handle input, and write a function to do that. Checking a Y/N response for a 'y' and an 'n' is annoying. Users prefer there to be a default behavior that requires only one answer. For example, if the default is N, then the user can type 'Y' or just hit enter, defaulting to N. This will reduce the amount of code you have to write, as well.</p>\n\n<p>Writing a function for this should be easy and obvious. You can return a boolean true for yes, false for no, and use that inside an <code>if</code> statement:</p>\n\n<pre><code>if ask_yorn(\"Are you sure you with to play this game?\"):\n print(\"Okay lets continue then!\")\n print(\"\")\n print(\"\")\n print(\"\"\"~~~~~~~~~~MENU~~~~~~~~~~\"\"\")\n # ...\nelse:\n quit(\"Thank you for playing!\")\n</code></pre></li>\n<li><p>A same suggestion applies to numeric text entry for selecting from a menu. Write a function that takes a maximum value, a prompt, and keeps looping until a valid input is found. Call it <code>get_number(3, \"> \")</code>. Let the return value be the integer result.</p></li>\n<li><p>Collapse your various <code>xxx_easy/med/hard</code> functions into code as much as you can. Your only change seems to be the board size, so why not just create a size variable, or use the <code>len(board)</code> directly to know how many rows/columns there are? </p></li>\n<li><p>Write a function to handle getting a board command, checking it against the valid list of commands, and returning a valid result. It should just loop until something valid happens, either <code>up</code>, <code>down</code>, etc or an <code>exit</code>. </p></li>\n<li><p>Finally, stop using <code>current[0]</code> and <code>current[1]</code>. You are storing values into the list, then unpacking the elements of the list each time. You should consider some of these possibilities:</p>\n\n<ul>\n<li>Declare <code>global position</code> (instead of current) and stop passing arguments.</li>\n<li>Create a <code>namedtuple</code> and use <code>current.x, current.y</code>.</li>\n<li>Create a tuple and pass it directly.</li>\n<li>Create <code>global X</code> and <code>global Y</code> and pass them directly.</li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-22T21:02:03.583",
"Id": "212023",
"ParentId": "211571",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T19:44:40.997",
"Id": "211571",
"Score": "4",
"Tags": [
"python",
"game",
"tkinter"
],
"Title": "Treasure hunt game"
} | 211571 |
<h1>Introduction</h1>
<p>I decided to try Kotlin because of its forgiving nature to long-time Java users. I implemented a few introductory sorting algorithms and would like to have them reviewed, not just to ensure that I'm applying Kotlin correctly, but also to improve my style and get rid of any potential bugs.</p>
<p>I have made use of a few extension functions to make the code more readable and all relevant source code will be posted in this question.</p>
<p><strong>Note:</strong> I tagged it as Java as well, because someone familiar with Java can easily get into Kotlin if they see how easy it is to read Kotlin. Anything applicable in Java can almost always be applied directly to Kotlin code.</p>
<h1>Project Structure</h1>
<h2>Main files</h2>
<pre><code>+- meta
| +- annotations
| | +- ComparisonSort
| | +- StableSort
| +- Complexity
+- sort
| +- AbstractSort
| +- BubbleSort
| +- InsertionSort
| +- MergeSort
| +- QuickSort
| +- SelectionSort
+- util
+- ArrayHelper
</code></pre>
<h2>Tests</h2>
<pre><code>+- sort
| +- AbstractSortTest
| +- BubbleSortTest
| +- InsertionSortTest
| +- MergeSortTest
| +- QuickSortTest
| +- SelectionSortTest
+- util
+- ArrayHelperTest
</code></pre>
<h1>My concerns</h1>
<p>Besides being undocumented (I didn't add comments because I think the code is already readable enough), I think I might my code could be a bit better organized. If there are some test cases that I forgot to include, please bring it to my attention. General comments on any potential issues, preferences are always welcome.</p>
<h1>The Source Code</h1>
<h2>ArrayHelper.kt</h2>
<p>Note that all the functions here are extension functions. These methods are tacked on top of the existing ones in the <code>Array.kt</code> class provided in the library.
</p>
<pre><code>package com.github.hungrybluedev.util
import kotlin.random.Random
fun <T> Array<T>.swap(i: Int, j: Int) {
val tmp = this[i]
this[i] = this[j]
this[j] = tmp
}
fun <T> Array<T>.shuffle() {
shuffle(0, size)
}
fun <T> Array<T>.shuffle(lower: Int, upper: Int) {
for (index in lower + 2 until upper) {
swap(index, Random.nextInt(index))
}
}
fun <T : Comparable<T>> Array<T>.isSorted(): Boolean {
return isSorted(0, size)
}
fun <T : Comparable<T>> Array<T>.isSorted(
lower: Int,
upper: Int
): Boolean {
for (index in lower + 1 until upper) {
if (this[index - 1] > this[index]) {
return false
}
}
return true
}
fun <T> Array<T>.isSorted(
comparator: Comparator<T>,
lower: Int,
upper: Int
): Boolean {
for (index in lower + 1 until upper) {
if (comparator.compare(this[index - 1], this[index]) > 0) {
return false
}
}
return true
}
</code></pre>
<h2>AbstractSort.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
import com.github.hungrybluedev.meta.Complexity
abstract class AbstractSort(val complexity: Complexity) {
fun <T : Comparable<T>> sort(arr: Array<T>) {
sort(arr, naturalOrder(), 0, arr.size)
}
fun <T : Comparable<T>> sort(arr: Array<T>, lower: Int, upper: Int) {
sort(arr, naturalOrder(), lower, upper)
}
fun <T> sort(arr: Array<T>, comparator: Comparator<T>) {
sort(arr, comparator, 0, arr.size)
}
abstract fun <T> sort(
arr: Array<T>,
comparator: Comparator<T>,
lower: Int,
upper: Int
)
}
</code></pre>
<h2>BubbleSort.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
import com.github.hungrybluedev.meta.Complexity
import com.github.hungrybluedev.meta.annotatioins.ComparisonSort
import com.github.hungrybluedev.meta.annotatioins.StableSort
import com.github.hungrybluedev.util.swap
@ComparisonSort
@StableSort
class BubbleSort : AbstractSort(Complexity.QUADRATIC) {
override fun <T> sort(
arr: Array<T>,
comparator: Comparator<T>,
lower: Int,
upper: Int
) {
var sorted = 0
do {
var swapped = false
for (i in lower until upper - 1 - sorted) {
if (comparator.compare(arr[i], arr[i + 1]) > 0) {
arr.swap(i, i + 1)
swapped = true
}
}
sorted++
} while (swapped)
}
}
</code></pre>
<h2>InsertionSort.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
import com.github.hungrybluedev.meta.Complexity
import com.github.hungrybluedev.meta.annotatioins.ComparisonSort
import com.github.hungrybluedev.meta.annotatioins.StableSort
@StableSort
@ComparisonSort
class InsertionSort : AbstractSort(Complexity.QUADRATIC) {
override fun <T> sort(
arr: Array<T>,
comparator: Comparator<T>,
lower: Int,
upper: Int
) {
for (j in lower + 1 until upper) {
val key = arr[j]
var i = j - 1
while (i >= lower && comparator.compare(key, arr[i]) < 0) {
arr[i + 1] = arr[i--]
}
arr[i + 1] = key
}
}
}
</code></pre>
<h2>MergeSort.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
import com.github.hungrybluedev.meta.Complexity
import com.github.hungrybluedev.meta.annotatioins.ComparisonSort
import com.github.hungrybluedev.meta.annotatioins.StableSort
@StableSort
@ComparisonSort
class MergeSort : AbstractSort(Complexity.LINEARITHMIC) {
private fun <T> merge(
from: Array<T>,
to: Array<T>,
p: Int,
q: Int,
r: Int,
comparator: Comparator<T>
) {
var i = p
var j = p
var k = q
while (i < q && k < r) {
to[j++] = if (comparator.compare(from[i], from[k]) < 0)
from[i++]
else
from[k++]
}
while (i < q) {
to[j++] = from[i++]
}
while (k < r) {
to[j++] = from[k++]
}
}
private fun <T> internalSort(
arrA: Array<T>,
arrB: Array<T>,
comparator: Comparator<T>,
p: Int,
r: Int
) {
if (r - p <= 1) {
return
}
val q = p + ((r - p) shr 1)
internalSort(arrB, arrA, comparator, p, q)
internalSort(arrB, arrA, comparator, q, r)
merge(arrB, arrA, p, q, r, comparator)
}
override fun <T> sort(
arr: Array<T>,
comparator: Comparator<T>,
lower: Int,
upper: Int
) {
val copy = arr.clone()
internalSort(arr, copy, comparator, lower, upper)
}
}
</code></pre>
<h2>QuickSort.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
import com.github.hungrybluedev.meta.Complexity
import com.github.hungrybluedev.meta.annotatioins.ComparisonSort
import com.github.hungrybluedev.util.swap
import kotlin.random.Random
@ComparisonSort
class QuickSort : AbstractSort(Complexity.LINEARITHMIC) {
private fun <T> partition(
arr: Array<T>,
lower: Int,
upper: Int,
comparator: Comparator<T>
): Int {
val pivot = arr[lower + Random.nextInt(upper - lower + 1)]
var p = lower - 1
var q = upper + 1
while (true) {
while (comparator.compare(arr[++p], pivot) < 0);
while (comparator.compare(arr[--q], pivot) > 0);
if (p >= q) {
return q
}
arr.swap(p, q)
}
}
private fun <T> internalSort(
arr: Array<T>,
comparator: Comparator<T>,
lower: Int,
upper: Int
) {
if (lower >= upper) {
return
}
val pivot = partition(arr, lower, upper, comparator)
internalSort(arr, comparator, lower, pivot)
internalSort(arr, comparator, pivot + 1, upper)
}
override fun <T> sort(
arr: Array<T>,
comparator: Comparator<T>,
lower: Int,
upper: Int
) {
internalSort(arr, comparator, lower, upper - 1)
}
}
</code></pre>
<h2>Complexity.kt</h2>
<pre><code>package com.github.hungrybluedev.meta
enum class Complexity {
LOGARITHMIC,
LINEAR,
LINEARITHMIC,
QUADRATIC,
CUBIC
}
</code></pre>
<h2>ComparisonSort.kt</h2>
<pre><code>package com.github.hungrybluedev.meta.annotatioins
annotation class ComparisonSort
</code></pre>
<h2>StableSortSort.kt</h2>
<pre><code>package com.github.hungrybluedev.meta.annotatioins
annotation class StableSort
</code></pre>
<h1>Tests</h1>
<h2>AbstractSortTest.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
import com.github.hungrybluedev.meta.Complexity
import com.github.hungrybluedev.util.isSorted
import com.github.hungrybluedev.util.shuffle
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import kotlin.random.Random
abstract class AbstractSortTest<out T : AbstractSort>(private val sorter: T) {
private val size = when (sorter.complexity) {
Complexity.QUADRATIC -> 20_000
Complexity.LINEARITHMIC -> 1_000_000
else -> 10_000
}
@Test
internal fun emptyTest() {
val arr = arrayOf<Int>()
sorter.sort(arr)
assertArrayEquals(arrayOf<Int>(), arr)
}
@Test
internal fun singleElementTest() {
val arr = arrayOf(1)
sorter.sort(arr)
assertArrayEquals(arrayOf(1), arr)
}
@Test
internal fun sortedElementsTest() {
val arr = arrayOf(1, 2, 5, 7)
sorter.sort(arr)
assertArrayEquals(arrayOf(1, 2, 5, 7), arr)
}
@Test
internal fun unsortedElementsTest() {
val arr = arrayOf(7, 2, 5, 1)
sorter.sort(arr)
assertArrayEquals(arrayOf(1, 2, 5, 7), arr)
}
@Test
internal fun reverseOrderTest() {
val arr = arrayOf(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
sorter.sort(arr)
assertArrayEquals(arrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), arr)
}
@Test
internal fun partialSortTest() {
val arr = arrayOf(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
sorter.sort(arr, 4, 9)
assertArrayEquals(arrayOf(9, 8, 7, 6, 1, 2, 3, 4, 5, 0), arr)
}
@Test
internal fun comparatorDescendingTest() {
val arr = arrayOf(9, 3, 4, 6, 2, 1, 0, 5, 7, 8)
sorter.sort(arr, reverseOrder())
assertArrayEquals(arrayOf(9, 8, 7, 6, 5, 4, 3, 2, 1, 0), arr)
}
@Test
internal fun comparatorPartialDescendingTest() {
val arr = arrayOf(3, 0, 1, 2, 4, 8, 5, 9, 7, 6)
sorter.sort(arr, 0, 5)
sorter.sort(arr, reverseOrder(), 5, 10)
assertArrayEquals(arrayOf(0, 1, 2, 3, 4, 9, 8, 7, 6, 5), arr)
}
@Test
internal fun repeatedElementsTest() {
val arr = arrayOf(0, 0, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 9, 9)
val cpy = arr.clone()
cpy.shuffle()
sorter.sort(cpy)
assertArrayEquals(arr, cpy)
}
@Test
internal fun randomDistinctArrayTest() {
val arr = Array(size) { x -> x }
sorter.sort(arr)
assertTrue(arr.isSorted())
}
@Test
internal fun randomRepeatedTest() {
val arr = Array(size) { Random.nextInt(size) }
sorter.sort(arr)
assertTrue(arr.isSorted())
}
@Test
internal fun descendingTest() {
val arr = Array(size) { x -> size - x }
sorter.sort(arr)
assertTrue(arr.isSorted())
}
}
</code></pre>
<h2>BubbleSortTest.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
internal class BubbleSortTest : AbstractSortTest<BubbleSort>(BubbleSort())
</code></pre>
<h2>InsertionSortTest.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
internal class InsertionSortTest : AbstractSortTest<InsertionSort>(InsertionSort())
</code></pre>
<h2>MergeSortTest.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
internal class MergeSortTest : AbstractSortTest<MergeSort>(MergeSort())
</code></pre>
<h2>QuickSortTest.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
internal class QuickSortTest : AbstractSortTest<QuickSort>(QuickSort())
</code></pre>
<h2>SelectionSortTest.kt</h2>
<pre><code>package com.github.hungrybluedev.sort
internal class SelectionSortTest : AbstractSortTest<SelectionSort>(SelectionSort())
</code></pre>
<h2>ArrayHelperTest.kt</h2>
<pre><code>package com.github.hungrybluedev.util
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class ArrayHelperTest {
@Test
internal fun smallAscendingTest() {
val arr = arrayOf(1, 2, 3, 4, 5)
assertTrue(arr.isSorted())
assertTrue(arr.isSorted(0, arr.size))
assertTrue(arr.isSorted(naturalOrder(), 0, arr.size))
}
@Test
internal fun smallDescendingTest() {
val arr = arrayOf(9, 7, 6, 4, 3, 2)
assertFalse(arr.isSorted())
assertFalse(arr.isSorted(0, arr.size))
assertTrue(arr.isSorted(reverseOrder(), 0, arr.size))
}
}
</code></pre>
| [] | [
{
"body": "<p>Few typical problems:</p>\n\n<ul>\n<li><p><code>if (comparator.compare(from[i], from[k]) < 0)</code> causes merge sort to lose stability. If the elements compare equal, the value from the right subarray is merged first.</p></li>\n<li><p>Insertion sort implementation is suboptimal: at each iteration of</p>\n\n<pre><code> while (i >= lower && comparator.compare(key, arr[i]) < 0) {\n</code></pre>\n\n<p><em>two</em> conditions are tested. It is possible to test only <em>one</em>. In pseudocode:</p>\n\n<pre><code> if key <= array[lower]\n // Don't bother to compare values. We are guaranteed\n // that everything is not less than the key. Just shift.\n while i >= lower\n arr[i + 1] = arr[i--]\n else\n // Don't bother to check indices. We are guaranteed\n // to not fall off: the first element is less than the key,\n // and naturally guard the insertion.\n while key < arr[i]\n arr[i + 1] = arr[i--]\n arr[i + 1] = key;\n</code></pre>\n\n<p>It doesn't change the quadratic nature of the insertion, but improves the bottomline. After all, not everything is about big-oh. In the rare cases we resort to insertion sort, this may give a crucial performance boost.</p></li>\n<li><p>Quick sort implementation is equally suboptimal. Standard ways to improve performance are</p>\n\n<ul>\n<li><p>Do not recur into small partitions; the call becomes too expensive. Define a threshold, say <code>k</code>, and if the partition is smaller than <code>k</code> return immediately. Once the initial invocation of <code>internalSort</code> returns, run an insertion sort. It will complete in <span class=\"math-container\">\\$O(nk)\\$</span> (do you see why?). BTW, it <em>is</em> one of the rare occasions where resorting to insertion sort is beneficial.</p></li>\n<li><p>Eliminate the tail recursive call. Java doesn't do tail recursion elimination, and I am sure Kotlin doesn't either. Keep in mind that you want to recur into a <em>smaller</em> partition, and handle the larger one in the loop.</p></li>\n<li><p>I am not sure that the random pivot selection strategy is sound.</p></li>\n</ul></li>\n<li><p>I don't see the benefits of <code>enum class Complexity</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T03:53:50.697",
"Id": "409120",
"Score": "0",
"body": "Really great insights! Can you please provide links to some resources so that I can learn more about such optimizations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T05:40:48.247",
"Id": "409125",
"Score": "2",
"body": "@HungryBlueDev Give the praise where it belongs. [Here](https://www.youtube.com/playlist?list=PLHxtyCq_WDLXryyw91lahwdtpZsmo4BGD) are the insights from a master; what the entire course. He uses C++, but you'll see soon that the language doesn't matter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:03:09.743",
"Id": "211585",
"ParentId": "211573",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211585",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:07:28.933",
"Id": "211573",
"Score": "2",
"Tags": [
"java",
"algorithm",
"sorting",
"kotlin"
],
"Title": "Sorting algorithms in Kotlin - Bubble, Insertion, Selection, Merge and Quick sort"
} | 211573 |
<p>I created a simple program to simulate the Ant's path. The Ant moves north, west, east and south. Each time the Anth moves to an "uncharted" location, I build a Square and give it a color. Each time the Ant steps in a square, the square changes color and the Ant rotates 90° and keeps her track. I use a <code>Stack</code> where I push my <code>Squares</code>. The <code>steps</code> list is something I need to keep track of <a href="https://en.wikipedia.org/wiki/Langton%27s_ant" rel="nofollow noreferrer">the path of the Ant</a>. I need to find when the Path stabilizes (Roughly after 10000 steps) and the Ant moves in a uniform manner.</p>
<p>It works great until 10<sup>6</sup> (takes 5 minutes to run). After that it takes more than 14 hours to get to the 10<sup>7</sup> mark. I don't get why it takes so much more time, shouldn't it just take <strong>10 × time it took to get to 10<sup>6</sup> iterations</strong> assuming my algorithm is <strong>o(n)</strong>?</p>
<p>I would like to keep the approach single threaded. What can I optimize?</p>
<hr>
<pre><code>enum Orientation{
NORTH, WEST, SOUTH, EAST
}
</code></pre>
<hr>
<pre><code>public class Square {
public int x, y;
// White = 0, Black = 1
public int color = 0;
}
</code></pre>
<hr>
<pre><code>int color = 0;
int x = 0, y = 1;
Stack<Square> squares = new Stack<Square>();
Orientation orientation = Orientation.NORTH;
List<Orientation> steps = new List<Orientation>();
for (int i = 0, counter = 0; i < 10000000; ++i, ++counter)
{
// First
if(i == 0)
{
squares.Push(new Square() { x = 0, y = 1, color = 1 });
// Rotate
orientation = Rotate(orientation, color == 0 ? true : false);
steps.Add(orientation);
continue;
}
// Move step
if (orientation == Orientation.NORTH) y += 1;
if (orientation == Orientation.EAST) x -= 1;
if (orientation == Orientation.WEST) x += 1;
if (orientation == Orientation.SOUTH) y -= 1;
// Check what the step has
Square s = squares.Where(square => square.x == x && square.y == y).DefaultIfEmpty(null).FirstOrDefault();
// if null create one and rotate
if (s == null)
{
squares.Push(CreateSquare(x, y, 1));
orientation = Rotate(orientation, true);
steps.Add(orientation);
}else if(s.color == 1)
{
s.color = 0;
orientation = Rotate(orientation, false);
steps.Add(orientation);
}else
{
s.color = 1;
orientation = Rotate(orientation, true);
steps.Add(orientation);
}
// 10^6 mark
if (i == 999999)
{
blackSquaresAt100k = squares.Where(sqa => sqa.color == 1).Count();
Console.WriteLine(blackSquaresAt100k);
}
// 10^7 mark
if (i == 9999999)
{
blackSquaresAt1M = squares.Where(sqa => sqa.color == 1).Count();
int totalNrOfBlackSquares = (blackSquaresAt1M - blackSquaresAt100k) * 12 + blackSquaresAt1M;
Console.WriteLine(totalNrOfBlackSquares);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:19:38.243",
"Id": "409105",
"Score": "2",
"body": "The question is on the verge of being closed for _Lack of concrete context_ reason. At least, what is `squares`? Please add _all_ necessary details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:26:11.330",
"Id": "409106",
"Score": "0",
"body": "@vnp Let me know if you need anything more"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:06:03.187",
"Id": "409111",
"Score": "4",
"body": "Well now we see that since `squares` is a `Stack`, and `Stack.Where` takes linear time, the entire thing cannot be \\$O(n)\\$. Use `Set`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:23:43.747",
"Id": "409112",
"Score": "0",
"body": "Your code is still incomplete; for example, the `Orientation` enum is never defined, and the `color` variable referenced in the `if(i==0)` block isn't declared. But as @vnp pointed out, your main performance problem is almost certainly the `.Where`, which may iterate the entire collection. Switching to a `Dictionary<Tuple<int, int>, Square>`, and using `TryGetValue` will help you a lot. You may still have issues related to memory allocation as the collections grow very large, however."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:29:31.657",
"Id": "409113",
"Score": "0",
"body": "Thank you guys for the suggestion I shall try it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:57:56.390",
"Id": "409115",
"Score": "0",
"body": "@benj2240 It doesnt grow that large, after 14hours running it was still at 120Mb"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T00:10:22.683",
"Id": "409117",
"Score": "0",
"body": "@benj2240 Now it runs less than 30 seconds. Wow, major flaw in my code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T04:39:47.263",
"Id": "409297",
"Score": "0",
"body": "Based on your last two comments (I mean no insult to you)... But it reminded me of the scene in The Lord of the Rings, where it takes hours for the trees to say \"Hello\" to one another. Whereas in English it is accomplished in seconds. --- You managed to create the tree language!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T11:21:24.433",
"Id": "409327",
"Score": "0",
"body": "@Svek Haha, would never be insulted by one of my fav movies of all time"
}
] | [
{
"body": "<h2>Optimisation</h2>\n\n<blockquote>\n <p>I use a <code>Stack</code> where I push my <code>Squares</code>.</p>\n</blockquote>\n\n<p>A stack is the correct data structure when you want last-in-first-out behaviour. Is that the behaviour you need here?</p>\n\n<blockquote>\n <p>It works great until 10<sup>6</sup> (takes 5 minutes to run).</p>\n</blockquote>\n\n<p>That is a long way from \"<em>great</em>\". 10<sup>6</sup> shouldn't take 10 seconds. Use the right data structure for the task, which here is something with amortised constant time insertion and lookup.</p>\n\n<h2>Other notes</h2>\n\n<blockquote>\n<pre><code>public class Square { \n public int x, y;\n // White = 0, Black = 1\n public int color = 0;\n}\n</code></pre>\n</blockquote>\n\n<p>Why are all of the fields mutable? Why is there no explicit constructor? Rather than using a 32-bit type to store a single bit and needing to document the legal values, why not use a 1-bit type (i.e. <code>bool isBlack</code>)?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>int color = 0;\n</code></pre>\n</blockquote>\n\n<p>Does this need such a wide scope?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>for (int i = 0, counter = 0; i < 10000000; ++i, ++counter)\n</code></pre>\n</blockquote>\n\n<p>What is the purpose of <code>counter</code>? As far as I can tell, it isn't used anywhere.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> squares.Push(new Square() { x = 0, y = 1, color = 1 });\n</code></pre>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n<pre><code> squares.Push(CreateSquare(x, y, 1));\n</code></pre>\n</blockquote>\n\n<p>Why the discrepancy?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> orientation = Rotate(orientation, color == 0 ? true : false);\n</code></pre>\n</blockquote>\n\n<p><code>condition ? true : false</code> is an unnecessarily long way of writing <code>condition</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (orientation == Orientation.NORTH) y += 1;\n if (orientation == Orientation.EAST) x -= 1;\n if (orientation == Orientation.WEST) x += 1;\n if (orientation == Orientation.SOUTH) y -= 1;\n</code></pre>\n</blockquote>\n\n<p>This is precisely the kind of thing that <code>switch</code> statements were invented to handle.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // if null create one and rotate\n if (s == null)\n {\n squares.Push(CreateSquare(x, y, 1));\n orientation = Rotate(orientation, true);\n steps.Add(orientation);\n }else if(s.color == 1)\n {\n s.color = 0;\n orientation = Rotate(orientation, false);\n steps.Add(orientation);\n }else\n {\n s.color = 1;\n orientation = Rotate(orientation, true);\n steps.Add(orientation);\n }\n</code></pre>\n</blockquote>\n\n<p>Don't repeat yourself. This could be refactored as</p>\n\n<pre><code> if (s == null)\n {\n s = new Square { x = x, y = y, color = 0 };\n squares.Push(s);\n }\n\n orientation = Rotate(orientation, s.color == 0);\n steps.Add(orientation);\n s.color = 1 - s.color;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> blackSquaresAt100k = squares.Where(sqa => sqa.color == 1).Count();\n</code></pre>\n</blockquote>\n\n<p><code>Count</code> has an overload which takes a condition, so <code>enumerable.Where(foo).Count()</code> can be refactored to <code>enumerable.Count(foo)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-28T11:52:30.767",
"Id": "212373",
"ParentId": "211576",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T20:38:57.167",
"Id": "211576",
"Score": "3",
"Tags": [
"c#",
"time-limit-exceeded",
"simulation"
],
"Title": "Langton's Ant simulation"
} | 211576 |
<p>I am very new to Java and its collections and I'm trying to figure out "best" way to populate an <code>ArrayList<Byte></code> in Java. In particular, I'm trying to take a 32 bit number, divide it into bytes, and put it into big-endian order into the list. I'm not particularly interested in hyper-optimizing in this case; I'd rather the code be clean and readable.</p>
<p>I've got a couple issues that are obvious to me, but the biggest one is that I hate the fact that I am initializing the list with bogus values before I update them. But my choices seem to be that, or adding the elements in ascending order, which seems to make the code to extract the bytes significantly more complex.</p>
<p>Am I missing a better solution?</p>
<pre><code>public void Add32BitValue(int value) {
// Adding 4 elements first to the list, so that
// I can modify them so they'll be in big endian
// order.
// (The code to directly add them in big endian
// order seems much more complex.)
for (int i=0; i<4; i++) {
list.add((byte)0);
}
// Now that the elements are in the arraylist, they
// can be set.
for (int i = 3; i >= 0; i--) {
list.set(list.size() + i - 4, (byte)value);
value = value >> 8;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T21:41:41.830",
"Id": "409100",
"Score": "1",
"body": "What's the context? Why do you want bytes in a list? How many of these integers and lists are you going to have?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:03:09.017",
"Id": "409103",
"Score": "0",
"body": "One list. Not sure about the exact size range, but I'm looking at maybe 100K bytes. I'm implementing something similar to a stack (but would like to be able to look at a bunch of stuff by index rather than popping/peeking groups of 20-100 values). I'm not wholly convinced that this is the right approach/collection...but that's okay. I'm doing this as a project to become familiar with Java vs my normal environment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:05:46.453",
"Id": "409104",
"Score": "0",
"body": "I was thinking about using Stack initially (since my project is an interpreter, and this is the stack)...but since different objects that are of different sizes and purposes can go on the stack and need to have their bytes readable, it didn't seem like a great fit...though, thinking about it I guess I could create some kind of parent class that goes into the stack...but that's also weird to me, because the objects wouldn't really have much in common (other than that they can both go on the stack.)"
}
] | [
{
"body": "<p>Assuming your list was defined elsewhere, you could append the bytes of value as follows. </p>\n\n<pre><code>for(int i = 3; i >= 0; i--) {\n list.add((byte)((value >>> (i*8)) & 0xFF));\n}\n</code></pre>\n\n<ul>\n<li>It avoids pre-populating the arraylist</li>\n<li>It avoids resetting the byte already stored</li>\n<li>It avoids storing the shifted value back in value</li>\n<li>It uses a logical right shift to avoid sign extension of negative integers</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:09:47.037",
"Id": "409214",
"Score": "0",
"body": "Yep...we're just assuming the list defined externally. This makes sense. For some reason, it didn't occur to me to utilize the index in the amount to shift."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:17:22.167",
"Id": "409239",
"Score": "0",
"body": "@Beska glad it helped."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T23:53:40.790",
"Id": "211588",
"ParentId": "211577",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T21:02:02.323",
"Id": "211577",
"Score": "0",
"Tags": [
"java",
"integer",
"collections",
"serialization"
],
"Title": "Breaking a 32-bit value into bytes for an ArrayList"
} | 211577 |
<p>Cats is a library that provides abstractions for functional programming in Scala.</p>
<p>The name is a playful shortening of the word <em>category</em>.</p>
<p><a href="https://typelevel.github.io/cats/" rel="nofollow noreferrer">Official Website</a></p>
<p><a href="https://github.com/non/cats" rel="nofollow noreferrer">Official Repository</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:43:31.473",
"Id": "211582",
"Score": "0",
"Tags": null,
"Title": null
} | 211582 |
Cats is a library that provides abstractions for functional programming in Scala. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:43:31.473",
"Id": "211583",
"Score": "0",
"Tags": null,
"Title": null
} | 211583 |
<p>I participate in competitive programming contests, and I found myself implementing and re-implementing graphs constantly. So I decided to create a reusable implementation of a Graph class, and implement some common methods for it, including DFS, BFS, and Dijkstras.</p>
<p>Are there any edge cases that my code misses? Is there anything I could do to improve it?</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
public class Graph<T> {
public class Node {
public T value;
public Map<Integer, Integer> edges;
public Node(T value) {
this.value = value;
edges = new HashMap<>();
}
}
public List<Node> nodes;
public boolean directed;
public int numNodes = 0;
public int numEdges = 0;
public Graph() {
this(false);
}
public Graph(boolean directed) {
nodes = new ArrayList<>();
this.directed = directed;
}
public void addNode(T value) {
nodes.add(new Node(value));
}
public void connect(int i, int j, int weight) {
nodes.get(i).edges.put(j, weight);
if (!directed)
nodes.get(j).edges.put(i, weight);
}
public class DijkstrasNode extends Node {
int dist = -1;
boolean visited = false;
DijkstrasNode previous;
public DijkstrasNode(T value) {
super(value);
}
public DijkstrasNode(Node node) {
super(node.value);
this.edges = node.edges;
}
}
public void processBFS(int source, BiConsumer<Node, Integer> consumer) {
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[nodes.size()];
q.add(source);
while (!q.isEmpty()) {
int id = q.poll();
if (visited[id])
continue;
visited[id] = true;
Node n = nodes.get(id);
consumer.accept(n, id);
for (int c: n.edges.keySet())
q.add(c);
}
}
public void processDFS(int source, BiConsumer<Node, Integer> consumer) {
Stack<Integer> q = new Stack<>();
boolean[] visited = new boolean[nodes.size()];
q.push(source);
while (!q.isEmpty()) {
int id = q.pop();
if (visited[id])
continue;
visited[id] = true;
Node n = nodes.get(id);
consumer.accept(n, id);
for (int c: n.edges.keySet())
q.add(c);
}
}
public List<DijkstrasNode> dijkstras(int source) {
List<DijkstrasNode> djk = nodes.stream().map(DijkstrasNode::new).collect(Collectors.toList());
djk.get(source).dist = 0;
PriorityQueue<DijkstrasNode> q = new PriorityQueue<>((i, j) -> i.dist - j.dist);
q.add(djk.get(source));
int visitCount = 0;
while (!q.isEmpty() && visitCount < djk.size()) {
DijkstrasNode n = q.poll();
if (n.visited)
continue;
n.visited = true;
visitCount++;
for (int child : n.edges.keySet()) {
DijkstrasNode cn = djk.get(child);
if (!cn.visited && (cn.dist == -1 || n.dist + n.edges.get(child) < cn.dist)) {
if (cn.dist != -1)
q.remove(cn);
cn.dist = n.dist + n.edges.get(child);
cn.previous = n;
q.add(cn);
}
}
}
return djk;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:27:13.227",
"Id": "409159",
"Score": "0",
"body": "Nice. You might consider also implementing the graph as a 2d array, which might have performance benefits in some cases"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:57:23.340",
"Id": "409209",
"Score": "0",
"body": "@RobAu will that necessarily help with Dijkstras? I've heard that adjacency matrixes are less efficient for Dijkstras."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:11:23.170",
"Id": "409216",
"Score": "0",
"body": "Performance is a function of a lot of factors, for example the sparsity of the graph, the implementation, cache and memory-efficiency etc."
}
] | [
{
"body": "<p>Just a small remark design-wise:</p>\n\n<p>I think you should not extend <code>Node</code> to <code>DijkstraNode</code>, but rather have a <code>Node<Dijkstra></code>. Or, if you intent to store info in the DijkstraNode, have a <code>Node<Dijkstra<T>></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:29:30.313",
"Id": "211603",
"ParentId": "211584",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T22:48:59.087",
"Id": "211584",
"Score": "4",
"Tags": [
"java",
"algorithm",
"graph"
],
"Title": "Implementation of generic Graph class and Dijkstras"
} | 211584 |
<p>I would like your feedback on any improvements that can be made to this Hangman game I have written in C. Specifically, improvements in terms of runtime and code organization. This game was a nice way for me to learn more about the features of the C language, specifically pointers, and thus I have heavily commented the code I have written for the purposes of learning.</p>
<p>Below are the source files and the CMakeLists file (which includes many runtime Clang sanitizers enabled). Alternatively, the code can be easily compiled with the following: <code>cc *.c -o hangman && ./hangman</code></p>
<p><strong>main.c</strong></p>
<pre><code>/**
* * Hangman in C *
* O(1) lookup using pointers to 26 letters which each have a state
* A letter is either _ (not picked, default), or the letter itself
* I was inspired by seeing many other Hangman implementations which
* relied on a multiple layers of iteration, this aims to be 'simple'
* and 'idiomatic', by using a different approach.
*
* @date 1/15/19
* @author Faraz Fazli
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "rng.h"
#include "utils.h"
/**
* Use enum to replace "magic numbers" instead of #define or const
* Ref: Practice of Programming, p.21
*/
enum {
ALPHABET_SIZE = 26,
TOTAL_TRIES = 10,
};
// Words the program chooses from
static char *words[] = {"racing", "magic", "bow", "racecar"};
int main() {
char letters[ALPHABET_SIZE];
// Let's set 'letters' to be composed of just _
// This will later be changed as the user guesses
memset(letters, '_', ALPHABET_SIZE);
init_rng();
// Total number of elements in our array
size_t total_elems = sizeof(words)/sizeof(words[0]);
char *word = words[rand_to(total_elems)];
size_t word_size = strlen(word) + 1; // includes NUL character
// Here I used 'malloc' instead of VLA
char **word_to_guess = malloc(word_size * sizeof(word));
size_t word_len = strlen(word); // excludes NUL
// point each element to the appropriate letter in our array
for (size_t i = 0; i < word_len; i++) {
word_to_guess[i] = &letters[from_a(word[i])];
}
int tries = 0;
size_t num_previous_underscores = word_len;
print_count_underscores(word_to_guess);
fputs("\nPick a letter: ", stdout);
// Could replace getchar() with fgets and parse each letter
// which may serve better in the future
int current_letter;
while ((current_letter = getchar()) != EOF) {
if (!isalpha(current_letter)) {
// Simply continue - printing here causes bugs
continue;
}
// convert to lower case
current_letter = tolower(current_letter);
// distance from 'a'
size_t letter_pos = from_a(current_letter);
// Letter has already been picked if it is in array
if (letters[letter_pos] == current_letter) {
puts("Please pick a different letter.");
continue;
} else {
// Change underscore to the letter
letters[letter_pos] = (char) current_letter;
}
// Finds if word still has underscores, and print word state
size_t num_underscores = print_count_underscores(word_to_guess);
// If letter has no correct guesses from this turn, increment tries
if (num_underscores == num_previous_underscores) {
tries++;
}
num_previous_underscores = num_underscores;
// Win if no underscores left
if (num_underscores == 0) {
puts("-> YOU WIN!");
break;
}
if (tries < TOTAL_TRIES) {
printf("\nTries Remaining: %d\n", TOTAL_TRIES - tries);
fputs("Pick a letter: ", stdout);
} else {
puts("No tries left! Game Over!");
break;
}
}
free(word_to_guess);
}
</code></pre>
<p><strong>rng.c</strong></p>
<pre><code>#include "rng.h"
#include <time.h>
void init_rng(void) {
srand((unsigned int) time(NULL));
}
size_t rand_to(size_t max) {
return (unsigned long) rand() / (RAND_MAX / max + 1);
}
</code></pre>
<p><strong>rng.h</strong></p>
<pre><code>#pragma once
#include <stdlib.h>
// Initializes random number generator
void init_rng(void);
/**
* Helper method for Random Number Generation
* @param max - max number
* @return between 0 to max
*/
size_t rand_to(size_t max);
</code></pre>
<p><strong>utils.c</strong></p>
<pre><code>#include <stdio.h>
#include "utils.h"
size_t print_count_underscores(const char **word_to_guess) {
size_t num_underscores = 0;
while (*word_to_guess) {
printf("%c ", **word_to_guess);
if (**word_to_guess++ == '_') {
num_underscores++;
}
}
return num_underscores;
}
size_t from_a(int letter) {
return (size_t) abs(letter - 'a');
}
</code></pre>
<p><strong>utils.h</strong></p>
<pre><code>#pragma once
#include <stdlib.h>
/**
* Prints the state of each letter and counts the number of underscores
* @param word_to_guess - word being guessed (array of pointers)
* @return underscore count
*/
size_t print_count_underscores(const char **word_to_guess);
/**
* Returns the distance from 'a'
* @param letter 'a' to 'z'
* @return 0 through 25
*/
size_t from_a(int letter);
</code></pre>
| [] | [
{
"body": "<p><strong>Overall</strong></p>\n\n<p>A quality effort.</p>\n\n<p>I especially like function documentation in the header files, where others can see it.</p>\n\n<hr>\n\n<p><strong><code>#pragma once</code></strong></p>\n\n<p><code>#pragma once</code> is not standard C. For higher portability, use code guards.</p>\n\n<hr>\n\n<p>Mostly minor stuff follows</p>\n\n<p><strong>Style</strong></p>\n\n<p><code>char **word_to_guess = malloc(word_size * sizeof(word));</code> <em>looks</em> wrong.<br>\nSuggest <code>char **word_to_guess = malloc(word_size * sizeof *word_to_guess);</code></p>\n\n<p><strong>Trouble with letters with <em>locales</em></strong></p>\n\n<p>Only important when outside C <em>locale</em>.</p>\n\n<p>In various <em>locales</em> <code>letters[letter_pos]</code> will become UB as <code>letters[]</code> is only good for the usual 26. Defensive coding would insure a valid index.</p>\n\n<p>In such <em>locales</em> <code>letters[letter_pos]</code> can have a negative value while the \"same\" <code>current_letter</code> is positive. Then <code>if (letters[letter_pos] == current_letter) {</code> will fail, even with the \"same\" letter. </p>\n\n<p>Perhaps cast:</p>\n\n<pre><code>// if (letters[letter_pos] == current_letter) \nif (letters[letter_pos] == (char) current_letter) \n</code></pre>\n\n<p><strong><code>len()</code> missing</strong></p>\n\n<p><code>len(words)</code> needs a definition.</p>\n\n<p><strong>Namespace</strong></p>\n\n<p><code>rng.h</code> declares <code>init_rng</code> and <code>rand_to</code>. Consider <code>rng_init()</code>, <code>rng_to()</code>.</p>\n\n<p><strong>One too many types, maybe</strong></p>\n\n<p><code>rand_to()</code> involves 3 types: <code>size_t, unsigned long, int</code>. The selection of <code>(unsigned long)</code> seems arbitrary. Recommend to use <code>size_t</code>. Note this code is weak unless <code>RAND_MAX</code> is much larger than <code>max</code>.</p>\n\n<pre><code>size_t rand_to(size_t max) {\n return (unsigned long) rand() / (RAND_MAX / max + 1);\n return (size_t) rand() / (RAND_MAX / max + 1);\n}\n</code></pre>\n\n<p>Deeper: <code>size_t</code> is a tricky type as its rank is not defined in relationship to the other <em>unsigned types</em>. <code>size_t</code> is often <code>unsigned long</code>, yet code should not rely on that. In this case we know <code>[0 <= rand() <= INT_MIN <= UINT_MAX]</code> and <code>[32767 <= RAND_MAX <= INT_MIN <= UINT_MAX]</code> and so could be more careful with the below, which is not to far off your original code. The care comes from <code>(size_t) rand()</code> could, in theory on a unicorn platform, truncate the value. A <code>(unsigned)</code> cast will never lose info here and get us into the nicely behaviored <em>unsigned</em> math. It is not excessive, like <code>unsigned long</code> may be. The division will push the math to wider unsigned types as needed.</p>\n\n<pre><code> return (unsigned) rand() / ((unsigned) RAND_MAX / max + 1u);\n</code></pre>\n\n<p><strong>Minor: <code>#include</code></strong></p>\n\n<p>I'd expect <code><stdlib.h></code> in <code>rng.c</code>. IMO, the standard includes found in the matching <code>\"rng.h\"</code> should not be relied on. As with such style issues: code to you group's coding guidelines.</p>\n\n<pre><code>#include \"rng.h\"\n#include <stdlib.h> // add\n#include <time.h>\n</code></pre>\n\n<p><strong><code>include</code> twice detection.</strong></p>\n\n<p>Take this idea or not: It is useful to detect if the matching header file suffers redundant inclusion as below. Within xxx.c, and only here, I find including xxx.h twice nicely exercises this.</p>\n\n<pre><code>#include \"rng.h\"\n#include \"rng.h\" // add\n#include <stdlib.h>\n#include <time.h>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:11:52.930",
"Id": "409396",
"Score": "0",
"body": "Hi @chux, I have definitely learned a lot from this answer. One question I had - what does \"include twice detection\" mean? Why would you suggest I include \"rng.h\" twice, and which file would I include it twice in? I have a \"#pragma once\" guard in place to protect against double inclusion. Does this notation help make something clear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:20:27.523",
"Id": "409398",
"Score": "0",
"body": "@Faraz An include file should not _need_ to be included twice, yet include files should tolerate being included twice, hence code guards. So if you inadvertently made an include file that was not tolerant of being included twice, how would that error be detected? The error might exist a long time before some code did so - a latent bug ( I despise those sleeping bugs.). By having xxx.c purposely include xxx.h twice, that tolerance is tested when the coder is messing with xxx.c/xxx.h. Of course other .c files need not purposely include xxx.h twice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:26:17.003",
"Id": "409400",
"Score": "0",
"body": "@Faraz Note again `#pragma once` is not standard, even though fairly common. Also if your test code did not have a `#pragma once` or code guard, how would this compilation fail? Perhaps not at all. If a `#pragma once` or code guard is important, it is useful for the compilation of xxx.c (or test code for xxx.c,xxx.h) to detect it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:42:34.243",
"Id": "409402",
"Score": "0",
"body": "Ok, and one other question - if I change `sizeof(words)/sizeof(words[0])` into a function-like macro such as `#define len(x) (((sizeof(x)))/(sizeof(x[0])))`, would you suggest placing it in the utils.h file or main.c from where it is being called?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T20:44:23.810",
"Id": "409405",
"Score": "0",
"body": "@Faraz `len` is too generic a name to be in any .h file. `#define` should `()` the `x` in both places: perhaps as .`(sizeof(x)/sizeof((x)[0]))` or `(sizeof(x)/sizeof(*(x)))`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T05:14:38.490",
"Id": "211595",
"ParentId": "211593",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T03:18:17.567",
"Id": "211593",
"Score": "3",
"Tags": [
"c",
"hangman",
"c99"
],
"Title": "Hangman written in C"
} | 211593 |
<p>My code can generate HTML table strings well, but it depends on JSON.NET.</p>
<p>I'm converting <code>IEnumerable</code> to an HTML table string using Json.NET but I think I shouldn't.</p>
<pre><code>void Main()
{
var datas = new[] { new {Name="Test"} };
var array = datas.ToArray().ToHtmlTable(); //Run Success
var set = datas.ToHashSet().ToHtmlTable();//Run Succes
var list = datas.ToList().ToHtmlTable(); //Run Succes
var enums = datas.AsEnumerable().ToHtmlTable(); //Run Succes
}
public static class HTMLTableHelper
{
public static string ToHtmlTable(this IEnumerable enums)
{
return ToHtmlTableConverter(enums);
}
public static string ToHtmlTable(this System.Data.DataTable dataTable)
{
return ConvertDataTableToHTML(dataTable);
}
private static string ToHtmlTableConverter(object enums)
{
var jsonStr = JsonConvert.SerializeObject(enums);
var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);
var html = ConvertDataTableToHTML(data);
return html;
}
private static string ConvertDataTableToHTML(System.Data.DataTable dt)
{
var html = new StringBuilder("<table>");
//Header
html.Append("<thead><tr>");
for (int i = 0; i < dt.Columns.Count; i++)
html.Append("<th>" + dt.Columns[i].ColumnName + "</th>");
html.Append("</tr></thead>");
//Body
html.Append("<tbody>");
for (int i = 0; i < dt.Rows.Count; i++)
{
html.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
html.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
html.Append("</tr>");
}
html.Append("</tbody>");
html.Append("</table>");
return html.ToString();
}
}
</code></pre>
<p>I think it is bad because <code>SerializeObject</code> to string could be <code>DeserializeObject</code> to <code>DataTable</code> is a waste of efficiency.</p>
<pre><code>var jsonStr = JsonConvert.SerializeObject(enums);
var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);
</code></pre>
<p>I want to remove dependencies on JSON.NET because it can reduce the size of the library.</p>
<p>Do you think I should replace them with something else if there is a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:47:21.763",
"Id": "409134",
"Score": "0",
"body": "mhmm... and yet you're using both `JsonNet` and `DataTable`s :-| Could you reframe your question please? Currently this is very confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:52:48.897",
"Id": "409136",
"Score": "0",
"body": "oh, I was afraid you might say that _but I don't know how to do it_ - we cannot help you with that because this is not a code writing site and we're not implementing new features or request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:55:27.797",
"Id": "409137",
"Score": "0",
"body": "Sorry,should I ask to StackOverflow? @t3chb0t"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:56:56.237",
"Id": "409138",
"Score": "0",
"body": "I don't think anybody would help you with that anywhere..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:58:16.053",
"Id": "409139",
"Score": "1",
"body": "@t3chb0t: others may not write the code for him, but they could still point him in the right direction..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:59:46.187",
"Id": "409140",
"Score": "0",
"body": "@PieterWitvoet Witvoet thanks, yes, i just hope someone point right direction"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:59:48.447",
"Id": "409141",
"Score": "2",
"body": "@ITWeiHan: read up on reflection. Also, Json.NET is open-source, so you can take a look at how `DeserializeObject` is implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:08:39.927",
"Id": "409143",
"Score": "1",
"body": "@PieterWitvoet as a matter of fact this could be even a valid Code Review question if asked differently... IT WeiHan you may usk us what we think of the JsonNet and DataTable dependency and why you think it's bad and what alternatives there might be or in which way would we improve that? I think this would be good question. But you have to tell us your reasoning etc. Simply saying I cannot use it is not enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:14:59.170",
"Id": "409145",
"Score": "0",
"body": "@t3chb0t , thanks , I try to fix my qeustion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:33:13.510",
"Id": "409147",
"Score": "4",
"body": "I made a couple small changes to your question so it doesn't sound like _please implement something else for me_ any more - I hope like the edit ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T08:36:09.503",
"Id": "409148",
"Score": "0",
"body": "@t3chb0t , thanks a lot !! I also trying search reflection docs now.Try to solve the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:16:23.037",
"Id": "409156",
"Score": "0",
"body": "@t3chb0t , Pieter Witvoet , thanks a lot,I do it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-25T13:20:30.777",
"Id": "451058",
"Score": "0",
"body": "You might want to check out T4 templates. You can come up with a more structured solution using that. Here is the link: https://docs.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2019"
}
] | [
{
"body": "<p>I can use reflection to solve it:</p>\n\n<pre><code>void Main()\n{\n var datas = new[] { new {Name=\"Test1\",Value=\"Test2\"} };\n var array = datas.ToArray().ToHtmlTable(); //Run Success\n var set = datas.ToHashSet().ToHtmlTable();//Run Succes\n var list = datas.ToList().ToHtmlTable(); //Run Succes\n var enums = datas.AsEnumerable().ToHtmlTable(); //Run Succes\n}\n\npublic static class HTMLTableHelper\n{\n public static string ToHtmlTable<T>(this IEnumerable<T> enums)\n {\n var type = typeof(T);\n var props = type.GetProperties();\n var html = new StringBuilder(\"<table>\");\n\n //Header\n html.Append(\"<thead><tr>\");\n foreach (var p in props)\n html.Append(\"<th>\" + p.Name + \"</th>\");\n html.Append(\"</tr></thead>\");\n\n //Body\n html.Append(\"<tbody>\");\n foreach (var e in enums)\n {\n html.Append(\"<tr>\");\n props.Select(s => s.GetValue(e)).ToList().ForEach(p => {\n html.Append(\"<td>\" + p + \"</td>\");\n }); \n html.Append(\"</tr>\");\n }\n\n html.Append(\"</tbody>\");\n html.Append(\"</table>\");\n return html.ToString();\n }\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody><tr><td>Test1</td><td>Test2</td></tr></tbody></table></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:15:24.100",
"Id": "211601",
"ParentId": "211598",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211601",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T07:18:22.550",
"Id": "211598",
"Score": "1",
"Tags": [
"c#",
".net"
],
"Title": "Convert IEnumerable to HTML table string"
} | 211598 |
<p>Can following code be called insertion sort?
I tried implementation according to my underdtanding...</p>
<pre><code>#include<iostream>
void insertionSort(int* array,int length){
for(int unsortedIndex=1; unsortedIndex<length;unsortedIndex++){
for(int sortedIndex=0; sortedIndex<unsortedIndex; sortedIndex++){
if(array[unsortedIndex] < array[sortedIndex]){
int temp = array[sortedIndex];
array[sortedIndex] = array[unsortedIndex];
array[unsortedIndex] = temp;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:27:16.340",
"Id": "409160",
"Score": "0",
"body": "have you actually checked that it sorts with decently large inputs (>10)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:28:35.043",
"Id": "409161",
"Score": "0",
"body": "no but will do now n let you know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:30:42.003",
"Id": "409162",
"Score": "0",
"body": "yeah it works fine"
}
] | [
{
"body": "<p>Yes, it is a variant that does the inner loop from the opposite side than the canonical version. </p>\n\n<p>This has the effect that you do a lot more comparisons than you would otherwise because you cannot early out as soon as you find where the element should be inserted to.</p>\n\n<p>Now for the nitpicks:</p>\n\n<p>There is no need to <code>#include<iostream></code> for this.</p>\n\n<p>Indentation isn't consistent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T10:37:17.887",
"Id": "211611",
"ParentId": "211602",
"Score": "1"
}
},
{
"body": "<p>This is <em>not</em> the standard <a href=\"https://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow noreferrer\">insertion sort algorithm</a>. Your algorithm has one feature in common with insertion sort, which is that it finds a small element and puts it at the front of the list. However, your algorithm does that by performing one swap, whereas the standard insertion sort does that by shifting all of the larger sorted elements over.</p>\n\n<p>One result of this difference is that your algorithm does not have all of the properties of insertion sort. In particular, your sorting algorithm is not <a href=\"https://en.wikipedia.org/wiki/Sorting_algorithm#Stability\" rel=\"nofollow noreferrer\">stable</a>. Stability is more of a concern when you are sorting objects rather than primitive ints, but still, this property is significant enough for me to consider your algorithm to fail to qualify as a variant of insertion sort.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T06:31:45.537",
"Id": "211661",
"ParentId": "211602",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211611",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:20:02.157",
"Id": "211602",
"Score": "0",
"Tags": [
"c++",
"sorting"
],
"Title": "Can this be called an insertionSort?"
} | 211602 |
<p>I have inherited the maintenance of a DXL script (for IBM Doors).</p>
<p>In this, I came across various examples of stuff that make me scratch my head. Take this example:</p>
<pre><code>int key = 3
print key
</code></pre>
<p>Running this in Doors, results in the expected output: 3.</p>
<p>However, in the documentation, we see that <code>key</code> is also the name of a function.</p>
<pre><code>Object o
for o in numberCache do {
// must cast the key command.
int i = (int key numberCache)
print i
}
</code></pre>
<p>While even the reference docs are full of examples declaring stuff like <code>string key</code>, <code>Item key</code> and so on, my concern is about safety.</p>
<p>What bad things I can run into, potentially, leaving the code I'm maintaining <em>as is</em>, knowing that it works, despite the fact it contains several functions using <code>key</code> as a variable name?</p>
<p>For instance, I'm really worried about this function right here:</p>
<pre><code>void linkFindObjects(string value, Module m, string key_name, Skip objectList)
{
Object o
string key, key2, key3
bool match1 = false
bool match2 = false
bool match = false
for o in m do {
key = probeAttr_(o, key_name)
if(key == value)
{
put (objectList, o, o)
}
}
}
</code></pre>
<p>My concern is that in DXL parenthesis are not mandatory: as you can see in the example, casting <code>key(numberCache)</code> can be simplified in <code>key numberCache</code>. When declaring the first three strings, the only thing preventing the whole code to blow up seems to be the comma. Please ignore for now the fact that the code declares a lot of unused stuff. It is as I got it.</p>
<p>Am I worrying too much?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:41:50.060",
"Id": "409164",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>Of course, it's bad mojo to use predefined key words as variable names, and yes, this might bring you into trouble. </p>\n\n<p>About \"key\": key is only defined for skip lists (perm: <code>_x key (Skip)</code>) and for the internal perm <code>HttpHeaderEntryString_ key ()</code>. It is not possible to cast a Skip list to a string, the code <code>Skip sk = create(); string s = \"hello \" sk \"!\"</code> will not be valid, so there is almost no danger that the interpreter wants to make a string concatenation when you have the code <code>xx = key sk</code>, even when key is defined as a string variable. </p>\n\n<p>So, in this case, you are more or less safe.<code>string key key2 key3</code> will give you a plain old syntax error that you can easily detect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T11:37:17.823",
"Id": "409328",
"Score": "0",
"body": "by the way, there is a good post about DXL ambiguity at https://www.ibm.com/developerworks/community/forums/html/topic?id=8ef3a679-8599-4779-bfaa-f108bd6697b4"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T11:27:32.970",
"Id": "211678",
"ParentId": "211604",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211678",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:33:27.217",
"Id": "211604",
"Score": "0",
"Tags": [
"type-safety",
"dxl"
],
"Title": "Potential type-safety issues on object parsing function in DXL"
} | 211604 |
<p>I used vtk python examples to write this function where it produces two lines with respect to a reference point like <code>[0, 0, 0]</code>. This function will return an actor where it can be used later in a render scene.
Here's my actor producer function (most of the code is not mine):</p>
<pre><code>import vtk
import random as rnd
def two_line(p0, p1):
# Create the polydata where we will store all the geometric data
linesPolyData = vtk.vtkPolyData()
# Create three points
origin = [0.0, 0.0, 0.0]
# p0 = [1.0, 0.0, 0.0]
# p1 = [0.0, 1.0, 0.0]
# Create a vtkPoints container and store the points in it
pts = vtk.vtkPoints()
pts.InsertNextPoint(origin)
pts.InsertNextPoint(p0)
pts.InsertNextPoint(p1)
# Add the points to the polydata container
linesPolyData.SetPoints(pts)
# Create the first line (between Origin and P0)
line0 = vtk.vtkLine()
line0.GetPointIds().SetId(0, 0) # the second 0 is the index of the Origin in linesPolyData's points
line0.GetPointIds().SetId(1, 1) # the second 1 is the index of P0 in linesPolyData's points
# Create the second line (between Origin and P1)
line1 = vtk.vtkLine()
line1.GetPointIds().SetId(0, 0) # the second 0 is the index of the Origin in linesPolyData's points
line1.GetPointIds().SetId(1, 2) # 2 is the index of P1 in linesPolyData's points
# Create a vtkCellArray container and store the lines in it
lines = vtk.vtkCellArray()
lines.InsertNextCell(line0)
lines.InsertNextCell(line1)
# Add the lines to the polydata container
linesPolyData.SetLines(lines)
namedColors = vtk.vtkNamedColors()
# Create a vtkUnsignedCharArray container and store the colors in it
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
try:
colors.InsertNextTupleValue(namedColors.GetColor3ub("DarkRed"))
colors.InsertNextTupleValue(namedColors.GetColor3ub("Gold"))
except AttributeError:
# For compatibility with new VTK generic data arrays.
colors.InsertNextTypedTuple(namedColors.GetColor3ub("DarkRed"))
colors.InsertNextTypedTuple(namedColors.GetColor3ub("Gold"))
# Color the lines.
# SetScalars() automatically associates the values in the data array passed as parameter
# to the elements in the same indices of the cell data array on which it is called.
# This means the first component (red) of the colors array
# is matched with the first component of the cell array (line 0)
# and the second component (green) of the colors array
# is matched with the second component of the cell array (line 1)
linesPolyData.GetCellData().SetScalars(colors)
# Setup the visualization pipeline
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(linesPolyData)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetLineWidth(1)
return actor
</code></pre>
<p>Then i tried to pass this actor to a rendere function, Here it is:</p>
<pre><code>def render_scene(my_actor_list):
renderer = vtk.vtkRenderer()
for arg in my_actor_list:
renderer.AddActor(arg)
namedColors = vtk.vtkNamedColors()
renderer.SetBackground(namedColors.GetColor3d("SlateGray"))
window = vtk.vtkRenderWindow()
window.SetWindowName("Colored Lines")
window.AddRenderer(renderer)
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(window)
# Visualize
window.Render()
interactor.Start()
</code></pre>
<p>In the last part i will use these two function to create many actors and render all of them in one scene. Here is the main function to do this:</p>
<pre><code>if __name__ == '__main__':
gen = 1000000
lst = []
for i in range(gen):
up = rnd.randint(-5, 5)
low = rnd.randint(-5, 5)
p0 = [rnd.uniform(low, up), rnd.uniform(low, up), rnd.uniform(low, up)]
p1 = [rnd.uniform(low, up), rnd.uniform(low, up), rnd.uniform(low, up)]
my_actor = two_line(p0, p1)
lst.append(my_actor)
render_scene(lst)
</code></pre>
<p>These codes will work perfectly if i use a relatively small number of generations, e.g. <code>gen = 1000</code>, but when the <code>gen=1000000</code> the render scene become very laggy. Is there any better way to pass objects to a render scene using functions to produce those objects?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T09:50:34.390",
"Id": "211606",
"Score": "3",
"Tags": [
"python",
"opengl"
],
"Title": "Using a large number of actors in one render scene with vtk python"
} | 211606 |
<blockquote>
<p>Developer Assignment - Family And Relations</p>
<p>Going through the old stuff in his attic, Indiana comes across a chart
which looks like a family tree of multiple generations which shows his
ancestors. Excited by the discovery, he decides to digitize the family
tree and utilize it to identify relationships of a person with another
on the family tree. Indiana has approached you to help him write a
command-line application to convert the family tree into some digital
format.</p>
<p><strong>Model the family tree such that:</strong></p>
<p>● Given an input in a format</p>
<p><code>Person=Alex Relation=Brothers</code></p>
<p>Expected Output should be</p>
<p><code>Brothers=John,Joe</code></p>
<p><code>$ run_application</code></p>
<p>Input: <code>Person=Alex Relation=Brothers</code></p>
<p>Output: <code>Brothers=John,Joe</code></p>
<p><strong>List of supported relations:</strong></p>
<ul>
<li>father </li>
<li>mother </li>
<li>brother(s) </li>
<li>sister(s) </li>
<li>son(s) </li>
<li>daughter(s) </li>
<li>cousin(s) </li>
<li>grandmother </li>
<li>grandfather </li>
<li>grandson(s) </li>
<li>grandaughter(s)</li>
<li>aunt(s) </li>
<li>uncle(s)</li>
</ul>
<p>Indiana notices that no two family members have the same name. Indiana
also realises that the information on the chart is a bit outdated. He
also need to add more information on the chart so that the information
is up to date.</p>
<p>● Given an input in a format</p>
<p><code>Husband=Bern Wife=Julia</code></p>
<p>The application should add Julia as a spouse for Bern.</p>
<p><code>Person=Bern Relation=Wife</code></p>
<p>Should return output as:</p>
<p><code>Wife=Julia</code></p>
<p><code>$ run_application</code></p>
<p>Input: <code>Husband=Bern Wife=Julia</code></p>
<p>Output: <code>Welcome to the family, Julia!</code></p>
<p>Input: <code>Person=Bern Relation=Wife</code></p>
<p>Output: <code>Wife=Julia</code></p>
<p>Indiana should also be able to add a child once its born to a mother.</p>
<p>● Given the input in a format</p>
<p>Input: <code>Mother=Zoe Son=Boris</code></p>
<p>Input: <code>Person=Paul Relation=Sons</code></p>
<p>Output: <code>Sons=Boris,Roger</code></p>
<p><code>$ run_application</code></p>
<p>Input: <code>Mother=Zoe Son=Boris</code></p>
<p>Output: <code>Welcome to the family, Boris!</code></p>
<p>Input: <code>Person=Paul Relation=Sons</code></p>
<p>Output: <code>Sons=Boris,Roger</code></p>
<p><strong>Assumption:</strong></p>
<ul>
<li>Names are unique. Any new member added will also have a unique name.</li>
</ul>
</blockquote>
<p>I have implemented the following solution.</p>
<pre><code>class Person {
private String name;
private Gender gender;
private List<Relation> relations = new ArrayList<>();
Person(String name, Gender gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Relation> getRelations() {
return relations;
}
public void setRelations(List<Relation> relations) {
this.relations = relations;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public void addRelation(Relation relation) {
relations.add(relation);
}
}
class Relation {
private TreeRelationType type;
private Person person1;
private Person person2;
Relation(TreeRelationType type, Person person1, Person person2) {
this.type = type;
this.person1 = person1;
this.person2 = person2;
}
public TreeRelationType getType() {
return type;
}
public void setType(TreeRelationType type) {
this.type = type;
}
public Person getPerson1() {
return person1;
}
public void setPerson1(Person person1) {
this.person1 = person1;
}
public Person getPerson2() {
return person2;
}
public void setPerson2(Person person2) {
this.person2 = person2;
}
}
enum TreeRelationType {
SPOUSE, PARENT, CHILD
}
enum Gender {
MALE, FEMALE
}
enum RelationType {
FATHER, MOTHER, BROTHER, SISTER, SON, DAUGHTER, COUSIN, GRANDMOTHER, GRANDFATHER, GRANDSON, GRANDDAUGHTER, AUNT, UNCLE, HUSBAND, WIFE
}
class InvalidInputException extends Exception {
static final long serialVersionUID = -3387516993334229948L;
public InvalidInputException(String message) {
super(message);
}
}
public class FamilyTree {
private Person root;
private Map<String, Boolean> visted = new HashMap<>();
public Person getRoot() {
return root;
}
public void setRoot(Person root) {
this.root = root;
}
private Gender fetchGender(RelationType type) {
if (RelationType.MOTHER.equals(type) || RelationType.DAUGHTER.equals(type) || RelationType.WIFE.equals(type))
return Gender.FEMALE;
else
return Gender.MALE;
}
private TreeRelationType fetchTreeRelationType(RelationType type) {
if (RelationType.MOTHER.equals(type) || RelationType.FATHER.equals(type))
return TreeRelationType.CHILD;
else if (RelationType.HUSBAND.equals(type) || RelationType.WIFE.equals(type))
return TreeRelationType.SPOUSE;
else
return TreeRelationType.PARENT;
}
public void addPerson(String name1, RelationType type1, String name2, RelationType type2)
throws InvalidInputException {
TreeRelationType relationType1 = fetchTreeRelationType(type1);
TreeRelationType relationType2 = fetchTreeRelationType(type2);
Gender gender1 = fetchGender(type1);
Gender gender2 = fetchGender(type2);
if (this.root == null) {
Person person1 = new Person(name1, gender1);
Person person2 = new Person(name2, gender2);
this.root = person1;
addRelation(relationType1, person1, relationType2, person2);
} else {
Person person1 = findPerson(this.root, name1);
if (person1 == null) {
throw new InvalidInputException("Invalid Input");
}
Person person2 = new Person(name2, gender2);
addRelation(relationType1, person1, relationType2, person2);
if (TreeRelationType.CHILD.equals(relationType1)) {
for (Relation relation : person1.getRelations()) {
if (TreeRelationType.SPOUSE.equals(relation.getType())) {
person1 = relation.getPerson2();
break;
}
}
addRelation(relationType1, person1, relationType2, person2);
}
}
}
private Person findPerson(Person cur, String name) {
this.visted.put(cur.getName(), Boolean.TRUE);
if (cur.getName().equals(name)) {
this.visted.clear();
return cur;
} else {
for (Relation relation : cur.getRelations()) {
Person person2 = relation.getPerson2();
if (!visted.containsKey(person2.getName())) {
Person person = findPerson(person2, name);
if (person != null) {
return person;
}
}
}
}
return null;
}
private void addRelation(TreeRelationType type1, Person person1, TreeRelationType type2, Person person2) {
Relation relation1 = new Relation(type1, person1, person2);
person1.addRelation(relation1);
Relation relation2 = new Relation(type2, person2, person1);
person2.addRelation(relation2);
}
private List<Person> fetchChildren(String name) throws InvalidInputException {
List<Person> children = new ArrayList<>();
Person person = findPerson(this.root, name);
if (person == null) {
throw new InvalidInputException("Invalid Input");
}
for (Relation relation : person.getRelations()) {
if (TreeRelationType.CHILD.equals(relation.getType())) {
children.add(relation.getPerson2());
}
}
return children;
}
private List<Person> fetchParents(String name) throws InvalidInputException {
List<Person> parents = new ArrayList<>();
Person person = findPerson(this.root, name);
if (person == null) {
throw new InvalidInputException("Invalid Input");
}
for (Relation relation : person.getRelations()) {
if (TreeRelationType.PARENT.equals(relation.getType())) {
parents.add(relation.getPerson2());
}
}
return parents;
}
private Person fetchFather(String name) throws InvalidInputException {
Person father = null;
List<Person> parents = fetchParents(name);
for (Person person : parents) {
if (Gender.MALE.equals(person.getGender()))
father = person;
}
return father;
}
private Person fetchMother(String name) throws InvalidInputException {
Person mother = null;
List<Person> parents = fetchParents(name);
for (Person person : parents) {
if (Gender.FEMALE.equals(person.getGender()))
mother = person;
}
return mother;
}
private List<Person> fetchSiblings(String name) throws InvalidInputException {
List<Person> siblings = new ArrayList<>();
Person father = fetchFather(name);
if (father != null) {
List<Person> children = fetchChildren(father.getName());
for (Person person : children) {
if (!person.getName().equals(name)) {
siblings.add(person);
}
}
}
return siblings;
}
private List<Person> fetchBrothers(String name) throws InvalidInputException {
List<Person> brothers = new ArrayList<>();
List<Person> siblings = fetchSiblings(name);
for (Person person : siblings) {
if (Gender.MALE.equals(person.getGender())) {
brothers.add(person);
}
}
return brothers;
}
private List<Person> fetchSisters(String name) throws InvalidInputException {
List<Person> sisters = new ArrayList<>();
List<Person> siblings = fetchSiblings(name);
for (Person person : siblings) {
if (Gender.FEMALE.equals(person.getGender())) {
sisters.add(person);
}
}
return sisters;
}
private List<Person> fetchSons(String name) throws InvalidInputException {
List<Person> sons = new ArrayList<>();
List<Person> children = fetchChildren(name);
for (Person person : children) {
if (Gender.MALE.equals(person.getGender())) {
sons.add(person);
}
}
return sons;
}
private List<Person> fetchDaugthers(String name) throws InvalidInputException {
List<Person> daughters = new ArrayList<>();
List<Person> children = fetchChildren(name);
for (Person person : children) {
if (Gender.FEMALE.equals(person.getGender())) {
daughters.add(person);
}
}
return daughters;
}
private List<Person> fetchCousins(String name) throws InvalidInputException {
List<Person> cousins = new ArrayList<>();
List<Person> parents = fetchParents(name);
for (Person person : parents) {
List<Person> siblings = fetchSiblings(person.getName());
for (Person sibling : siblings) {
List<Person> children = fetchChildren(sibling.getName());
cousins.addAll(children);
}
}
return cousins;
}
private List<Person> fetchGrandParents(String name) throws InvalidInputException {
List<Person> grandParents = new ArrayList<>();
List<Person> parents = fetchParents(name);
for (Person person : parents) {
grandParents.addAll(fetchParents(person.getName()));
}
return grandParents;
}
private Person fetchGrandMother(String name) throws InvalidInputException {
Person grandMother = null;
List<Person> grandParents = fetchGrandParents(name);
for (Person person : grandParents) {
if (Gender.FEMALE.equals(person.getGender())) {
grandMother = person;
}
}
return grandMother;
}
private Person fetchGrandFather(String name) throws InvalidInputException {
Person grandFather = null;
List<Person> grandParents = fetchGrandParents(name);
for (Person person : grandParents) {
if (Gender.MALE.equals(person.getGender())) {
grandFather = person;
}
}
return grandFather;
}
private List<Person> fetchGrandChildren(String name) throws InvalidInputException {
List<Person> children = fetchChildren(name);
List<Person> grandChildren = new ArrayList<>();
for (Person person : children) {
grandChildren.addAll(fetchChildren(person.getName()));
}
return grandChildren;
}
private List<Person> fetchGrandSons(String name) throws InvalidInputException {
List<Person> grandSons = new ArrayList<>();
List<Person> grandChildren = fetchGrandChildren(name);
for (Person person : grandChildren) {
if (Gender.MALE.equals(person.getGender())) {
grandSons.add(person);
}
}
return grandSons;
}
private List<Person> fetchGrandDaugthers(String name) throws InvalidInputException {
List<Person> grandDaugthers = new ArrayList<>();
List<Person> grandChildren = fetchGrandChildren(name);
for (Person person : grandChildren) {
if (Gender.FEMALE.equals(person.getGender())) {
grandDaugthers.add(person);
}
}
return grandDaugthers;
}
private List<Person> fetchAunts(String name) throws InvalidInputException {
List<Person> aunts = new ArrayList<>();
List<Person> parents = fetchParents(name);
for (Person person : parents) {
List<Person> siblings = fetchSiblings(person.getName());
for (Person sibling : siblings) {
if (Gender.FEMALE.equals(sibling.getGender())) {
aunts.add(sibling);
} else {
Optional<Person> spouce = Optional.ofNullable(fetchSpouce(sibling.getName()));
if (spouce.isPresent()) {
aunts.add(spouce.get());
}
}
}
}
return aunts;
}
private List<Person> fetchUncles(String name) throws InvalidInputException {
List<Person> uncles = new ArrayList<>();
List<Person> parents = fetchParents(name);
for (Person person : parents) {
List<Person> siblings = fetchSiblings(person.getName());
for (Person sibling : siblings) {
if (Gender.MALE.equals(sibling.getGender())) {
uncles.add(sibling);
} else {
Optional<Person> spouce = Optional.ofNullable(fetchSpouce(sibling.getName()));
if (spouce.isPresent()) {
uncles.add(spouce.get());
}
}
}
}
return uncles;
}
private Person fetchSpouce(String name) throws InvalidInputException {
Person spouce = null;
Person person = findPerson(this.root, name);
if (person == null) {
throw new InvalidInputException("Invalid Input");
}
for (Relation relation : person.getRelations()) {
if (TreeRelationType.SPOUSE.equals(relation.getType())) {
spouce = relation.getPerson2();
break;
}
}
return spouce;
}
public static void main(String args[]) throws InvalidInputException {
FamilyTree tree = new FamilyTree();
tree.addPerson("Evan", RelationType.HUSBAND, "Diana", RelationType.WIFE);
tree.addPerson("Evan", RelationType.FATHER, "John", RelationType.SON);
tree.addPerson("Evan", RelationType.FATHER, "Alex", RelationType.SON);
tree.addPerson("Evan", RelationType.FATHER, "Joe", RelationType.SON);
tree.addPerson("Evan", RelationType.FATHER, "Nisha", RelationType.DAUGHTER);
tree.addPerson("Alex", RelationType.HUSBAND, "Nancy", RelationType.WIFE);
tree.addPerson("Joe", RelationType.HUSBAND, "Niki", RelationType.WIFE);
tree.addPerson("Nisha", RelationType.WIFE, "Adam", RelationType.HUSBAND);
tree.addPerson("Alex", RelationType.FATHER, "Jacob", RelationType.SON);
tree.addPerson("Alex", RelationType.FATHER, "Shaun", RelationType.SON);
tree.addPerson("Joe", RelationType.FATHER, "Piers", RelationType.SON);
tree.addPerson("Joe", RelationType.FATHER, "Sally", RelationType.DAUGHTER);
tree.addPerson("Adam", RelationType.FATHER, "Ruth", RelationType.DAUGHTER);
tree.addPerson("Adam", RelationType.FATHER, "Paul", RelationType.SON);
tree.addPerson("Adam", RelationType.FATHER, "William", RelationType.SON);
tree.addPerson("Jacob", RelationType.HUSBAND, "Rufi", RelationType.WIFE);
tree.addPerson("Piers", RelationType.HUSBAND, "Pippa", RelationType.WIFE);
tree.addPerson("Sally", RelationType.WIFE, "Owen", RelationType.HUSBAND);
tree.addPerson("Ruth", RelationType.WIFE, "Neil", RelationType.HUSBAND);
tree.addPerson("Paul", RelationType.HUSBAND, "Zoe", RelationType.WIFE);
tree.addPerson("William", RelationType.HUSBAND, "Rose", RelationType.WIFE);
tree.addPerson("Jacob", RelationType.FATHER, "Bern", RelationType.SON);
tree.addPerson("Jacob", RelationType.FATHER, "Sophia", RelationType.DAUGHTER);
tree.addPerson("Piers", RelationType.FATHER, "Sarah", RelationType.DAUGHTER);
tree.addPerson("Paul", RelationType.FATHER, "Roger", RelationType.SON);
tree.addPerson("William", RelationType.FATHER, "Steve", RelationType.SON);
tree.addPerson("Sophia", RelationType.WIFE, "George", RelationType.HUSBAND);
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
try {
sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String inputString = sc.nextLine();
if (!inputString.isEmpty()) {
String[] input = inputString.split(" ");
if (input[0].equals("exit")) {
sc.close();
System.exit(0);
}
if (input[0].contains("Person")) {
String[] person = input[0].split("=");
String[] relation = input[1].split("=");
String name = person[1];
String value = relation[1].toUpperCase();
if (value.charAt(value.length() - 1) == 'S') {
value = value.substring(0, value.length() - 1);
}
RelationType relationType = RelationType.valueOf(value);
switch (relationType) {
case FATHER:
Optional<Person> father = Optional.ofNullable(tree.fetchFather(name));
if (father.isPresent()) {
System.out.println(relation[1] + "=" + tree.fetchFather(name).getName());
}
break;
case MOTHER:
Optional<Person> mother = Optional.ofNullable(tree.fetchMother(name));
if (mother.isPresent()) {
System.out.println(relation[1] + "=" + tree.fetchMother(name).getName());
}
break;
case BROTHER:
System.out.println(relation[1] + "=" + tree.fetchBrothers(name).stream()
.map(Person::getName).collect(Collectors.joining(",")));
break;
case SISTER:
System.out.println(relation[1] + "=" + tree.fetchSisters(name).stream().map(Person::getName)
.collect(Collectors.joining(",")));
break;
case SON:
System.out.println(relation[1] + "=" + tree.fetchSons(name).stream().map(Person::getName)
.collect(Collectors.joining(",")));
break;
case DAUGHTER:
System.out.println(relation[1] + "=" + tree.fetchDaugthers(name).stream()
.map(Person::getName).collect(Collectors.joining(",")));
break;
case COUSIN:
System.out.println(relation[1] + "=" + tree.fetchCousins(name).stream().map(Person::getName)
.collect(Collectors.joining(",")));
break;
case GRANDMOTHER:
Optional<Person> grandMother = Optional.ofNullable(tree.fetchGrandMother(name));
if (grandMother.isPresent()) {
System.out.println(relation[1] + "=" + tree.fetchGrandMother(name).getName());
}
break;
case GRANDFATHER:
Optional<Person> grandFather = Optional.ofNullable(tree.fetchGrandFather(name));
if (grandFather.isPresent()) {
System.out.println(relation[1] + "=" + tree.fetchGrandFather(name).getName());
}
break;
case GRANDSON:
System.out.println(relation[1] + "=" + tree.fetchGrandSons(name).stream()
.map(Person::getName).collect(Collectors.joining(",")));
break;
case GRANDDAUGHTER:
System.out.println(relation[1] + "=" + tree.fetchGrandDaugthers(name).stream()
.map(Person::getName).collect(Collectors.joining(",")));
break;
case AUNT:
System.out.println(relation[1] + "=" + tree.fetchAunts(name).stream().map(Person::getName)
.collect(Collectors.joining(",")));
break;
case UNCLE:
System.out.println(relation[1] + "=" + tree.fetchUncles(name).stream().map(Person::getName)
.collect(Collectors.joining(",")));
break;
case HUSBAND:
case WIFE:
Optional<Person> spouce = Optional.ofNullable(tree.fetchSpouce(name));
if (spouce.isPresent()) {
System.out.println(relation[1] + "=" + tree.fetchSpouce(name).getName());
}
break;
}
} else {
String name1 = input[0].split("=")[1];
String name2 = input[1].split("=")[1];
RelationType type1 = RelationType.valueOf(input[0].split("=")[0].toUpperCase());
RelationType type2 = RelationType.valueOf(input[1].split("=")[0].toUpperCase());
tree.addPerson(name1, type1, name2, type2);
System.out.println("Welcome to the family, " + name2 + "!");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
</code></pre>
<p>Is there a better way to solve this problem. Should I be improving anything here. The code was rejected by the company I applied for without any feedback. I am trying the find improvement areas.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:22:23.243",
"Id": "409199",
"Score": "0",
"body": "Is there a separation of the possible input roles vs the query-roles? I would restrict the input roles, else you could add a grandfather-grantson relation without intermediates and it becomes a increasingly difficutly problem. Also 'husband' and 'wife' are not in the list of supported roles."
}
] | [
{
"body": "<h2>Get the requirements clear!</h2>\n\n<ul>\n<li>What are valid input relations?</li>\n<li>What are valid query relations?</li>\n<li>Do relations need to be inferred? If so, </li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>//Does Julia have a son?\nf.addRelation(\"Husband=Bern Wife=Julia\");\nf.addRelation(\"Father=Bern Son=Evan\");\n\n//Does Julia have a son?\nf.addRelation(\"Father=Bern Son=Evan\");\nf.addRelation(\"Husband=Bern Wife=Julia\");\n</code></pre>\n\n<h2>Avoid repeating code</h2>\n\n<p>You have <strong>a lot</strong> of unnecessary repeating code.</p>\n\n<p>For example:</p>\n\n<pre><code>private Person fetchFather(String name) throws InvalidInputException {\n Person father = null;\n List<Person> parents = fetchParents(name);\n for (Person person : parents) {\n if (Gender.MALE.equals(person.getGender()))\n father = person;\n }\n return father;\n}\n\nprivate Person fetchMother(String name) throws InvalidInputException {\n Person mother = null;\n List<Person> parents = fetchParents(name);\n for (Person person : parents) {\n if (Gender.FEMALE.equals(person.getGender()))\n mother = person;\n }\n return mother;\n}\n</code></pre>\n\n<p>As you can see this is nearly identical. This can be simplified as:</p>\n\n<pre><code>private Person fetchParent(String name, Gender gender) throws InvalidInputException {\n Person parent = null;\n List<Person> parents = fetchParents(name);\n for (Person person : parents) {\n if (gender.equals(person.getGender()))\n parent = person;\n }\n return parent;\n }\n</code></pre>\n\n<p>As used:</p>\n\n<pre><code>private Person fetchFather(String name) throws InvalidInputException {\n return fetchParent(name, Gender.MALE);\n}\n</code></pre>\n\n<p>Following this pattern, you could also generalize more, as <code>TreeRelationType</code> can also be abstracted.</p>\n\n<h2>Adding relations don't need Gender</h2>\n\n<p>As you already know the persons Gender, the relation type does not any other information than PARENT / SIBLING / CHILD. The rest can be deduced. You should even store this relation in the Person itself, so that a Person contains three sets, <code>Set<Person> parents</code>, <code>Set<Person> children</code> and <code>Set<Person> siblings</code>. You must take care of keeping the symmetry of these relations. (adding a parent P to child C must also add child C to parent P).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T12:51:40.537",
"Id": "409189",
"Score": "0",
"body": "Do you feel, I could have solved any other way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:05:33.267",
"Id": "409193",
"Score": "0",
"body": "Yes. To be honest, I would not hire you as you currently create a lot of inefficient code. Try to see the abstract levels. And think about performance too (walking a tree vs getting from a Map, for example)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T11:51:34.633",
"Id": "211615",
"ParentId": "211609",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211615",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T10:24:37.180",
"Id": "211609",
"Score": "3",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Family Relationship Tree"
} | 211609 |
<p>I was just tempted to write a similar piece of code to the one presented in <a href="https://stackoverflow.com/a/3463944/2913106">this answer on SO</a> (posted below). The problem is having to discriminate between different cases where exactly <em>one</em> case is true. </p>
<p>In my experience <code>switch</code> statements are usually use to match the value of an expression against various constants. But in this case we use a <code>switch</code> statement to decide which of the conditions is <code>true</code>. To do this I would actually prefer using <code>if/else if</code> because <code>switch(true)</code> feels a little bit like an abuse of <code>switch</code>, but this is just a gut feeling. On the other hand I think this piece of code is still prefectly readable even with its seemingly unconventional use of a <code>switch</code> statement.</p>
<p>Are there any objective reasons why one would prefer <code>switch</code> over <code>if/else if</code> or vice versa when it comes to code quality, performance and readability?</p>
<pre><code>switch (true) {
case (amount >= 7500 && amount < 10000):
//code
break;
case (amount >= 10000 && amount < 15000):
//code
break;
//etc...
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T12:00:01.607",
"Id": "409184",
"Score": "0",
"body": "This question might be more on-topic over at https://SoftwareEngineering.StackExchange.com/ . However, **before posting please [follow their tour](https://SoftwareEngineering.StackExchange.com/tour) and read [\"How do I ask a good question?\"](https://SoftwareEngineering.StackExchange.com/help/how-to-ask), [\"What topics can I ask about here?\"](https://SoftwareEngineering.StackExchange.com/help/on-topic) and [\"What types of questions should I avoid asking?\"](https://SoftwareEngineering.StackExchange.com/help/dont-ask).**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T12:00:35.183",
"Id": "409185",
"Score": "4",
"body": "Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please [follow the tour](https://CodeReview.StackExchange.com/tour) and read [\"How do I ask a good question?\"](https://CodeReview.StackExchange.com/help/how-to-ask), [\"What topics can I ask about here?\"](https://CodeReview.StackExchange.com/help/on-topic) and [\"What types of questions should I avoid asking?\"](https://CodeReview.StackExchange.com/help/dont-ask)."
}
] | [
{
"body": "<p>Not really a review question. But as this will be closed I might as well give a quick answer. You should have asked this at SO.</p>\n\n<p><code>switch</code> statement are meant as a shortcut to long lists of simple <code>if (a == 1) else if (a == 2) else if (...</code>. They ended up in JS as that is what was needed to attract C/C++ coders to the language back in the day when JS was SLOW.</p>\n\n<p>There is nothing wrong with using them but in most cases you can simplify with <code>if else</code>.</p>\n\n<p>EG</p>\n\n<pre><code>// 3 logic operations\nif (a >= 75) { // 1\n if (a < 100) { ... } // 2 \n else if (a < 150) {/* 3 logic operations to get here */} // 3\n}\n\n// 8 logic operations\nswitch (true) { // this must evaluate on each case === true if you get to them\n case (a >= 75 && a < 100): // 1:(a >= 75) 2:(a < 100) 3:(&&) 4:(case === true)\n ...\n break;\n case (a >= 100 && a < 150): // 5:(a >= 100) 6:(a < 150) 7:(&&) 8:(case === true)\n /* 8 logic operations to get here */\n break;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:09:47.413",
"Id": "211619",
"ParentId": "211610",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211619",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T10:36:27.343",
"Id": "211610",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "Evaluating expressions in \"case\" vs using \"if/else if\""
} | 211610 |
<h2>Problem</h2>
<p>Given the following data:</p>
<pre><code>[
{
"users": [
{
"id": "07bde76f-aff0-407d-9241-a12b323d4af8",
"transactions": [
{
"category": "purchase"
},
{
"category": "unknown"
}
]
},
{
"id": "40aa040f-7961-4e06-a31b-32052be67fcc",
"transactions": [
{
"category": "sale"
},
{
"category": "unknown"
}
]
}
],
"groups": [
{
"id": "00c61181-b133-4be9-9d44-dc3c224b3beb",
"transactions": [
{
"category": "atm"
},
{
"category": "cash"
}
]
},
{
"id": "eb959ff1-da1d-41e5-b5b7-45fef3dbc2df",
"transactions": [
{
"category": "atm"
},
{
"category": "cash"
}
]
}
]
},
{
"users": [
{
"id": "af095f1c-fe43-43fb-9571-dabe2dd56bcf",
"transactions": [
{
"category": "bill"
}
]
}
],
"groups": [
{
"id": "c5bafe16-c5ec-428e-8c7c-30cbd9963750",
"transactions": [
{
"category": "fee"
},
{
"category": "cash"
}
]
}
]
}
]
</code></pre>
<p>... I want to produce the following output:</p>
<pre><code>{
"groups_atm": 2,
"groups_fee": 1,
"groups_cash": 3,
"users_purchase": 1,
"users_unknown": 2,
"users_bill": 1,
"users_sale": 1
}
</code></pre>
<h2>Implementation</h2>
<p>I've approached this by first mapping over transactions and summing their occurrences:</p>
<pre class="lang-js prettyprint-override"><code>const sum = (transactions) =>
transactions.map((transaction) => transaction.category).reduce((acc, transactionCategory) => {
return {
...acc,
[transactionCategory]: (acc[transactionCategory] || 0) + 1,
};
}, tally);
</code></pre>
<p>... then aggregating by scope ("user", "group") per element of the data list and merge the counts by category:</p>
<pre class="lang-js prettyprint-override"><code>const aggregate = (datum, tally) =>
['user', 'group'].reduce((acc, scope) => {
const aggregates = datum[`${scope}s`].reduce(
(agg, data) => sum(agg, data.transactions),
{},
);
return {
...acc,
[scope]: acc[scope] ? merge(acc[scope], aggregates) : aggregates,
};
}, tally);
</code></pre>
<pre class="lang-js prettyprint-override"><code>const difference = (arrA, arrB) => arrA.filter((x) => !arrB.includes(x));
const intersection = (arrA, arrB) => arrA.filter((x) => arrB.includes(x));
const merge = (objA, objB) => {
const acc = {};
const aKeys = Object.keys(objA);
const bKeys = Object.keys(objB);
intersection(aKeys, bKeys).forEach((key) => (acc[key] = objA[key] + objB[key]));
difference(aKeys, bKeys).forEach((key) => (acc[key] = objA[key]));
difference(bKeys, aKeys).forEach((key) => (acc[key] = objB[key]));
return acc;
};
</code></pre>
<p>... then re-reducing over the whole dataset:</p>
<pre class="lang-js prettyprint-override"><code>const aggregates = data.reduce((acc, datum) => aggregateScope(datum, acc), {});
</code></pre>
<p>... and finally reformatting the aggregates to match the expected output:</p>
<pre class="lang-js prettyprint-override"><code>const format = (aggregates) =>
Object.keys(aggregates).reduce((acc, scope) => {
Object.keys(aggregates[scope]).forEach((category) => {
acc[`${scope}_${category}`] = aggregates[scope][category];
});
return acc;
}, {});
</code></pre>
<h2>Questions</h2>
<ol>
<li>what are alternative ways of breaking down the problem?</li>
<li>what is it's Big O complexity? Can it be reduced?</li>
<li>can <code>merge</code> be avoided?</li>
<li>are there language features (JS/ES6) that can make this more idiomatic?</li>
<li>is "aggregation" the correct terminology?</li>
</ol>
| [] | [
{
"body": "<h1>Way way too complex</h1>\n\n<p>One way to help workout how to solve a problem is to solve it in your head (or on paper) first. That way you know the problem from the top to the bottom. Then use that approach in your script. </p>\n\n<p>The code looks like you started at the top with no clear idea of the solution, and solve many separate problems as you encountered them. The result is unreadable and way to complex. </p>\n\n<p>I could not make a good assessment due to its complexity and bugs.</p>\n\n<h2>Your code does not run.</h2>\n\n<ul>\n<li>The name <code>aggregateScope</code> in <code>aggregates</code> should be <code>aggregate</code></li>\n<li><code>sum</code> throws <code>TypeError map is not a function</code></li>\n</ul>\n\n<p>Patching those problems it still did not run.</p>\n\n<p>The hell of a zillion iterators is not easy to traverse so I stopped trying to work it out at that point.</p>\n\n<h2>Questions.</h2>\n\n<p>You have some questions.</p>\n\n<blockquote>\n <p>what are alternative ways of breaking down the problem?</p>\n</blockquote>\n\n<p>Its just a set of nested arrays and named objects. The names are fixed, so its just a process of stepping over each array in turn storing the counts in a named map (see example) </p>\n\n<blockquote>\n <p>what is it's Big O complexity? </p>\n</blockquote>\n\n<p>I am guessing its It more than <span class=\"math-container\">\\$O(n)\\$</span> and less than or equal to <span class=\"math-container\">\\$O(n^2)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the number of <code>category</code> items. As there is only a small sample dataset and the code does not work I can not give a accurate evaluation.</p>\n\n<p>I did count 18 different iteration function calls throughout your code. With 2 or 7 iterations each, nested to about 6 levels. If I use that and average <code>(2 + 7) / 2 = 4.5</code> per iterator then its 4.5<sup>6</sup> approx steps, so that's a big <span class=\"math-container\">\\$O(n^3)\\$</span> for the given dataset of 11 category items</p>\n\n<blockquote>\n <p>Can it be reduced?</p>\n</blockquote>\n\n<p>Yes, it can be O(n) as there is no need to search, and no need to compare items (see example).</p>\n\n<blockquote>\n <p>are there language features (JS/ES6) that can make this more idiomatic?</p>\n</blockquote>\n\n<ul>\n<li>Use <code>for of</code> loops to iterate.</li>\n<li>Use bracket notations to create named properties. </li>\n<li>Keep your functions ordered. From bottom to top, it makes it easier to locate functions and follow the code.</li>\n<li>No more than one iterator per line. You quickly lose track of how complex it gets.</li>\n</ul>\n\n<p>Is all that comes to mind, that and K.I.S.S. </p>\n\n<h2>An alternative example solution</h2>\n\n<p>I am not that conventional when it comes to code, so not quite idiomatic. less is good in my book and helps find the optimal <span class=\"math-container\">\\$O(n)\\$</span> solution.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function aggregateTransactionCategories(data, types) {\n const result = {};\n const mapCategories = (type, transactions) => {\n for (const cats of transactions) { \n const name = type + \"_\" + cats.category;\n result[name] = result[name] ? result[name] + 1 : 1;\n } \n }\n for (const type of types) {\n for (const entries of data) { \n for (const entry of entries[type]) { \n mapCategories(type, entry.transactions);\n }\n }\n }\n return result;\n}\n\nsetTimeout(() =>\n log(aggregateTransactionCategories( data, [\"groups\", \"users\"]))\n ,0\n);\n\n\n\n\nconst data = [{\n users: [\n { id: \"07bd\", transactions: [{category: \"purchase\"}, {category: \"unknown\"}] },\n { id: \"40aa\", transactions: [{category: \"sale\"}, {category: \"unknown\"}] }\n ],\n groups: [\n { id: \"00c6\", transactions: [{category: \"atm\"}, {category: \"cash\"}] },\n { id: \"eb95\", transactions: [{category: \"atm\"}, {category: \"cash\"}] }\n ]\n }, {\n users: [\n { id: \"af09\", transactions: [{category: \"bill\"}] }\n ],\n groups: [\n { id: \"c5ba\", transactions: [{category: \"fee\"}, {category: \"cash\"}] }\n ]\n }\n];\n\n\n//Just displays the result and not related to the problem\nfunction log(data) {\n for(const [name, value] of Object.entries(data)) {\n displayResult.appendChild(Object.assign(\n document.createElement(\"div\"),{ \n textContent : name + \": \" + value + \",\"\n }\n ))\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"displayResult\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T10:40:15.627",
"Id": "409320",
"Score": "0",
"body": "This is an excellent response. Thanks for taking the time to write it. You're correct in the way I approached this; I tried to break it down into smaller problems, lost sight of the overall problem and then awkwardly tried to piece it back together. The code _did_ run in my environment, but I mistranscribed it here. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:46:06.820",
"Id": "211627",
"ParentId": "211616",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T12:28:57.493",
"Id": "211616",
"Score": "2",
"Tags": [
"javascript",
"mapreduce"
],
"Title": "Efficiently aggregating nested data"
} | 211616 |
<p>I'm learning SQL using python library <code>pymysql</code>.</p>
<p>I wanted to make an INSERT statement that will update 3, 5 or 10 columns using the same code by just passing the Database name, the Columns name and the Values.</p>
<p>Thus I made this:</p>
<pre><code>def insert_statement(db,cols,values):
separator = ","
separator.join(cols)
statement = "INSERT INTO " + db + " (" + separator.join(cols) + ") VALUES ("
aux = []
for i in range(0,len(values)):
aux.append("%s")
statement = statement + separator.join(aux) + ")"
print (statement)
return statement
</code></pre>
<p>Passing the values, the function produces:</p>
<pre><code>>>>INSERT INTO Publicaciones (item_id,title,price) VALUES (%s,%s,%s)
</code></pre>
<p>Which works but, is it there a more pythonic way?</p>
| [] | [
{
"body": "<h3>SQL Injections</h3>\n\n<p>Even though you are having these proper placeholders for values, your code is still vulnerable to <a href=\"https://www.owasp.org/index.php/SQL_Injection\" rel=\"nofollow noreferrer\">SQL Injection</a> attacks as table and column names are not properly sanitized.</p>\n\n<p>As table and column names cannot be parameterized the usual way, you could validate them separately. For instance, you could check that the table and column names are simply <em>valid MySQL identifiers</em>:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/26497846/python-mysql-parameter-queries-for-dynamic-table-names\">Python MySQL parameter queries for dynamic table names</a></li>\n</ul>\n\n<hr>\n\n<h3>Object Relational Mappers</h3>\n\n<p>As I understand the purpose of the task is to learn how to interact with the MySQL database via Python MySQL database driver, but, in general, this kind of problems are already solved by different abstraction layer libraries or commonly called ORMs (Object Relational Mappers) like SQLAlchemy, Peewee or PonyORM) which provide an extra Python layer around Python-to-database communication allowing you to basically write SQL queries in Python.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:32:46.850",
"Id": "211621",
"ParentId": "211617",
"Score": "1"
}
},
{
"body": "<p>You’re not using <code>values</code> except for its length. But this should be the same length than <code>cols</code>, so use that instead.</p>\n\n<p>You also don't need a for-loop to build a list with the same element <code>N</code> times, list multiplication can handle that just fine.</p>\n\n<p>Lastly, I would use f-strings or at least <code>str.format</code> instead of string concatenation, it is prettyier.</p>\n\n<pre><code>def insert_statement(db, columns):\n column_names = ', '.join(columns)\n placeholders = ', '.join(['%s'] * len(columns))\n return f'INSERT INTO {db} ({column_names}) VALUES ({placeholders})'\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>>>> insert_statement('Publicationes', ['item_id', 'title', 'price'])\n'INSERT INTO Publicationes (item_id,title,price) VALUES (%s,%s,%s)'\n</code></pre>\n\n<p>Depending on your calling site, you can also make <code>columns</code> a variable length argument, it may be easier to use:</p>\n\n<pre><code>def insert_statement(db, *columns):\n column_names = ', '.join(columns)\n placeholders = ', '.join(['%s'] * len(columns))\n return f'INSERT INTO {db} ({column_names}) VALUES ({placeholders})'\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>>>> insert_statement('Publicationes', 'item_id', 'title', 'price')\n'INSERT INTO Publicationes (item_id,title,price) VALUES (%s,%s,%s)'\n</code></pre>\n\n<hr>\n\n<p>But you should limit yourself to only use this function using trusted input. If anything comming from a user enters here, this is a vulnerability waiting to happen:</p>\n\n<pre><code>>>> user_input = \"price) VALUES (42, 'foobar', 0.00); DROP TABLE Publicationes; -- Now this a vulnerability in disguise :\"\n>>> insert_statement('Publicationes', 'item_id', 'title', user_input)\n\"INSERT INTO Publicationes (item_id, title, price) VALUES (42, 'foobar', 0.00); DROP TABLE Publicationes; -- Now this a vulnerability in disguise :) VALUES (%s, %s, %s)\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T16:45:35.567",
"Id": "409245",
"Score": "0",
"body": "Yes! This was exactly what I was looking for. Thank you for all the information. And yes, this function will only be run by my server code without interaction with an user."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:35:50.137",
"Id": "211623",
"ParentId": "211617",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T12:45:02.520",
"Id": "211617",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"sql"
],
"Title": "Add variable columns to INSERT statement"
} | 211617 |
<p>Please review my generic implementation of the <a href="https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm" rel="nofollow noreferrer">Knuth-Morris-Pratt algorithm</a>. Its modified to search a source of indeterminate length in a memory efficient fashion.</p>
<pre><code>namespace Code
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A generic implementation of the Knuth-Morris-Pratt algorithm that searches,
/// in a memory efficient way, over a given <see cref="IEnumerator"/>.
/// </summary>
public static class KMP
{
/// <summary>
/// Determines whether the Enumerator contains the specified pattern.
/// </summary>
/// <typeparam name="T">The type of an item.</typeparam>
/// <param name="source">
/// The source, the <see cref="IEnumerator"/> must yield
/// objects of <typeparamref name="T"/>.
/// </param>
/// <param name="pattern">The pattern.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <returns>
/// <c>true</c> if the source contains the specified pattern;
/// otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">pattern</exception>
public static bool Contains<T>(
this IEnumerator source,
IEnumerable<T> pattern,
IEqualityComparer<T> equalityComparer = null)
{
if (pattern == null)
{
throw new ArgumentNullException(nameof(pattern));
}
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
return SearchImplementation(pattern, source, equalityComparer).Any();
}
/// <summary>
/// Identifies indices of a pattern string in source.
/// </summary>
/// <typeparam name="T">The type of an item.</typeparam>
/// <param name="patternString">The pattern string.</param>
/// <param name="source">
/// The source, the <see cref="IEnumerator"/> must yield
/// objects of <typeparamref name="T"/>.
/// </param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <returns>
/// A sequence of indices where the pattern can be found
/// in the source.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// patternSequence - The pattern must contain 1 or more elements.
/// </exception>
private static IEnumerable<long> SearchImplementation<T>(
IEnumerable<T> patternString,
IEnumerator source,
IEqualityComparer<T> equalityComparer)
{
// Pre-process the pattern
var preResult = GetSlide(patternString, equalityComparer);
var pattern = preResult.Pattern;
var slide = preResult.Slide;
var patternLength = pattern.Count;
if (pattern.Count == 0)
{
throw new ArgumentOutOfRangeException(
nameof(patternString),
"The pattern must contain 1 or more elements.");
}
var buffer = new Dictionary<long, T>(patternLength);
var more = true;
long i = 0; // index for source
int j = 0; // index for pattern
while (more)
{
more = FillBuffer(
buffer,
source,
i,
patternLength,
out T t);
if (equalityComparer.Equals(pattern[j], t))
{
j++;
i++;
}
more = FillBuffer(
buffer,
source,
i,
patternLength,
out t);
if (j == patternLength)
{
yield return i - j;
j = slide[j - 1];
}
else if (more && !equalityComparer.Equals(pattern[j], t))
{
if (j != 0)
{
j = slide[j - 1];
}
else
{
i = i + 1;
}
}
}
}
/// <summary>
/// Fills the buffer.
/// </summary>
/// <remarks>
/// The buffer is used so that it is not necessary to hold the
/// entire source in memory.
/// </remarks>
/// <typeparam name="T">The type of an item.</typeparam>
/// <param name="buffer">The buffer.</param>
/// <param name="s">The source enumerator.</param>
/// <param name="i">The current index.</param>
/// <param name="patternLength">Length of the pattern.</param>
/// <param name="value">The value retrieved from the source.</param>
/// <returns>
/// <c>true</c> if there is potentially more data to process;
/// otherwise <c>false</c>.
/// </returns>
private static bool FillBuffer<T>(
IDictionary<long, T> buffer,
IEnumerator s,
long i,
int patternLength,
out T value)
{
bool more = true;
if (!buffer.TryGetValue(i, out value))
{
more = s.MoveNext();
if (more)
{
value = (T)s.Current;
buffer.Remove(i - patternLength);
buffer.Add(i, value);
}
}
return more;
}
/// <summary>
/// Gets the offset array which acts as a slide rule for the KMP algorithm.
/// </summary>
/// <typeparam name="T">The type of an item.</typeparam>
/// <param name="pattern">The pattern.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <returns>A tuple of the offsets and the enumerated pattern.</returns>
private static (IReadOnlyList<int> Slide, IReadOnlyList<T> Pattern) GetSlide<T>(
IEnumerable<T> pattern,
IEqualityComparer<T> equalityComparer)
{
var patternList = pattern.ToList();
var slide = new int[patternList.Count];
int length = 0;
int i = 1;
while (i < patternList.Count)
{
if (equalityComparer.Equals(patternList[i], patternList[length]))
{
length++;
slide[i] = length;
i++;
}
else
{
if (length != 0)
{
length = slide[length - 1];
}
else
{
slide[i] = length;
i++;
}
}
}
return (slide, patternList);
}
}
}
</code></pre>
<p>I've used the non-generic <code>IEnumerator</code> for representing the source as it allows a wider breadth of enumerators to represent data, including the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.globalization.textelementenumerator?view=netframework-4.7.2" rel="nofollow noreferrer"><code>TextElementEnumerator</code></a>. This enables the generic implementation to be used trivially to search Unicode strings with different normalizations, e.g.</p>
<pre><code>namespace Code
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var testData = new List<(string Source, string Pattern)>
{
(string.Empty, "x"),
("y", "x"),
("x", "x"),
("yx", "x"),
("xy", "x"),
("aababccba", "abc"),
("1x2x3x4", "x"),
("x1x2x3x4x", "x"),
("1aababcabcd2aababcabcd3aababcabcd4", "aababcabcd"),
("ssstring", "sstring")
};
foreach(var d in testData)
{
var contains = Ext.Contains(d.Source, d.Pattern);
Console.WriteLine(
$"Source:\"{d.Source}\", Pattern:\"{d.Pattern}\", Contains:{contains}");
}
Console.ReadKey();
}
}
public static class Ext
{
public static bool Contains(
this string source,
string value,
CultureInfo culture = null,
StringComparer comparer = null)
{
comparer = comparer ?? StringComparer.Ordinal;
var sourceEnumerator = StringInfo.GetTextElementEnumerator(source);
var sequenceEnumerator = StringInfo.GetTextElementEnumerator(value);
var pattern = new List<string>();
while (sequenceEnumerator.MoveNext())
{
pattern.Add((string)sequenceEnumerator.Current);
}
return sourceEnumerator.Contains(pattern, comparer);
}
}
}
</code></pre>
<hr>
<p>This question was <a href="https://codereview.stackexchange.com/questions/211683/improved-knuth-morris-pratt-over-a-source-of-indeterminate-length">improved following the answer here</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:20:39.880",
"Id": "409224",
"Score": "2",
"body": "You may want to fix that typo in `KMP.Contains` (`pattern != null`) before an answer comes in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:02:30.340",
"Id": "409237",
"Score": "0",
"body": "@PieterWitvoet, sorry being really dense, I do see what you mean!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T08:00:06.547",
"Id": "409308",
"Score": "1",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>I'm looking at this block of code</p>\n\n<pre><code>while (more)\n{\n more = FillBuffer(buffer, source, i, patternLength, out T t);\n\n if (equalityComparer.Equals(pattern[j], t))\n {\n j++;\n i++;\n }\n\n more = FillBuffer(buffer, source, i, patternLength, out T t);\n\n ...\n}\n</code></pre>\n\n<blockquote>\n <p>I'm not convinced that it is correct...<br>\n Based how I read it, in the scenario that your <code>if</code> statement is <code>false</code>, then <code>FillBuffer</code> will <strong>return the same result</strong>, therefore it is a redundant call.</p>\n</blockquote>\n\n<p>I would consider changing the code to something like this...</p>\n\n<pre><code>while (more)\n{\n more = FillBuffer(buffer, source, i, patternLength, out T t);\n\n if (equalityComparer.Equals(pattern[j], t))\n {\n j++;\n i++;\n\n // now inside the if statement\n more = FillBuffer(buffer, source, i, patternLength, out T t);\n }\n\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T07:27:32.963",
"Id": "409304",
"Score": "0",
"body": "this makes logical sense to me and, it works in my testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T07:36:51.820",
"Id": "409307",
"Score": "0",
"body": "I've updated my question to incorporate these changes. In lieu of a more substantial update in the near future, I'll mark this as the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T03:59:02.607",
"Id": "211656",
"ParentId": "211622",
"Score": "5"
}
},
{
"body": "<p>Using an <code>IEnumerator</code> as first argument is quite unexpected, and makes this method more cumbersome to use than it needs to be. I'd stick to <code>IEnumerable<T></code>.</p>\n\n<p>It looks like <code>StringInfo.GetTextElementEnumerator</code> was an important motivation for this decision, but that's an old method that predates the introduction of generics. Why not write a wrapper method for that instead, one that returns <code>IEnumerable<string></code>?</p>\n\n<hr>\n\n<p>A few other points:</p>\n\n<ul>\n<li>You can use tuple deconstruction when calling <code>Slide</code>: <code>var (slide, pattern) = GetSlide(patternString, equalityComparer);</code>.</li>\n<li>It's good to see documentation, but some of it isn't very useful. If parameter documentation is just a repetition of the (already properly descriptive) parameter name then I would leave it out.</li>\n<li>I'd rename <code>i</code> to <code>sourceIndex</code> and <code>j</code> to <code>patternIndex</code>. Those comments already indicate that those names aren't sufficiently descriptive.</li>\n<li>The <code>culture</code> parameter in <code>Ext.Contains</code> is not used.</li>\n<li><code>TextElementEnumerator</code> has a <code>GetTextElement</code> method, which gives you <code>Current</code> as a <code>string</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T08:27:09.593",
"Id": "211666",
"ParentId": "211622",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "211666",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T13:35:27.297",
"Id": "211622",
"Score": "5",
"Tags": [
"c#",
"algorithm",
"strings",
"search"
],
"Title": "Knuth-Morris-Pratt over a source of indeterminate length"
} | 211622 |
<p>I am modelling a game which can be single (player1 vs player2) or double (pair 1 vs pair 2, where each pair contains 2 players) and each game has a score. The game is group and date based e.g. Group A on <code>date_n</code> can contain <code>n</code> games, on <code>date_m</code> can contain <code>m</code> games. In firestore, I use a <code>game</code> collection which looks like this:</p>
<pre><code>game =
{
date : '2019-01-14',
groupId : 'abcd',
player1 : 'Bob',
player2 : 'John', // can be null
player3 : 'Tony',
player4 : 'Mike', // can be null
score1 : 15,
score2 : 21
}
</code></pre>
<p>To easily query the ranking statistics (see below), I separate the game score int to two fields <code>score1</code> and <code>score2</code> where the final score would simply be <code>score1:score2</code>. Note that <code>player2</code> and <code>player4</code> are <code>null</code> for a single game, whereas <code>player1</code> and <code>player3</code> are never null/empty.</p>
<p>In a relational database e.g. SQL, it's just the same thing but in a game table.
So far so good I think! The tricky part is when querying and writing game statistics for each <strong>player</strong> and <strong>pair</strong>. The player/pair ranking stats are also time-range based e.g. <strong>daily/monthly/annually/alltime</strong>. To simplify, let's say I just want to rank each player/pair based on how many games each player/pair played and how many games each player/pair won.</p>
<p>In firestore, to avoid nesting the data too deeply, I use 8 collections:</p>
<pre><code>playerdailystats
playermonthlystats
playerannuallystats
playeralltimestats
pairdailystats
pairmonthlystats
pairannuallystats
pairalltimestats
</code></pre>
<p>and they all have the same structure, using <code>playerdailystats</code> as an example:</p>
<pre><code>playerdailystats =
{
date : '2019-01-14',
groupId : 'abcd',
Bob : {
played : 1,
won : 0,
},
John : {
played : 1,
won : 0
},
Tony : {
played : 1,
won : 1
},
Mike : {
played : 1,
won: 1
}
}
</code></pre>
<p>where each player field (e.g. <code>Bob</code>) is an <strong>map</strong> itself; and for monthly/annually stats collections the <strong>first day of the month/year</strong> will be used for the <code>date</code> field. For player/pair <code>alltimestats</code> collection, I chose a const date randomly e.g. 1983-10-06 for the date field though it doesn't require a date field but it's added in order to <strong>reuse the same query</strong> on all these stats collections (see below). For pairstats collections, just like player stats collections, each pair field is still a map though instead of using a player's name, I use a pair name which is combined of two player's names in the form of <code>name1,name2</code>. Since this can be in a form of either <code>player1Name,player2Name</code> or <code>player2Name,player1Name</code>, I sort two names first then use combined the names separated by comma.</p>
<p>Now I can use a single function to query the stats for daily, monthly, annually and alltime for each group with a given date because all these stats collections have the same structure. On the UI, it only shows one time-range stats at a time e.g. monthly. So the query function is like this (I am using dart but the language doesn't matter):</p>
<pre><code>Stream<Map<DateTime, List<Ranking>>> getRanking(String groupId, String collection) {
return Firestore.instance.collection(collection)
.where('groupId', isEqualto: groupId)
// why alltime stats collection need a date field.
.orderBy('date', descending: true)
.snapshots()
.take(5) // only show the latest 5 ranking.
.map((snaoshot){
// deserialize the data into domain models and return the result.
//in each stats collection, any fields that are not 'groupId' and not 'date' must be a stat field for a player or pair
});
}
</code></pre>
<p>The querying part isn't bad either since only one stats collection will queried at any time. Now the part that I think is potentially problematic: add a new game!
Any time adding a new <em>single or double</em> game for a given group, it doesn't only mean updating the <code>game</code> collection, but also mean updating <strong>ALL</strong> 4 or 8 stats collections of the group to keep the stats synchronised. Though I can again use one function to update all 8 collections due to their identical structure. The function for adding a new game result looks like this:</p>
<pre><code>Future<OperationResultBase> addNewGameResult(GameResult gameResult) async {
try {
// first add the game result
await Firestore.instance
.collection(FirestoreName.GAMES)
.add(gameResult.toJson());
// then update player daily stats
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PLAYERDAILYSTATS,
gameResult.date,
RankingBase.parseGameResultToPlayerRanking);
// then update player monthly stats
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PLAYERMONTHLYSTATS,
_firstDayOfTheMonth(gameResult.date),
RankingBase.parseGameResultToPlayerRanking);
// then update player annually stats
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PLAYERANNUALLYSTATS,
_firstDayOfTheYear(gameResult.date),
RankingBase.parseGameResultToPlayerRanking);
// then update player all time stats
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PLAYERALLTIMESTATS,
DateTime(1983, 10, 6), // use a special const date
RankingBase.parseGameResultToPlayerRanking);
// if it's a double game,
if (gameResult.isDoubleGame) {
// then update pair daily stats
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PAIRDAILYSTATS,
gameResult.date,
RankingBase.parseGameResultToPairRanking);
// then update pair monthly stats using 1st day of the month.
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PAIRMONTHLYSTATS,
_firstDayOfTheMonth(gameResult.date),
RankingBase.parseGameResultToPairRanking);
// then update pair annually stats using 1st date of the year.
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PAIRANNUALLYSTATS,
_firstDayOfTheYear(gameResult.date),
RankingBase.parseGameResultToPairRanking);
// then update pair all time stats using const date.
await _updateRankingStatsNoTransaction(
gameResult,
FirestoreName.PAIRALLTIMESTATS,
DateTime(1983, 10, 6),
RankingBase.parseGameResultToPairRanking);
}
return OperationResultBase.ok();
} on PlatformException catch (error) {
return OperationResultBase(success: false, message: error.message);
}
}
</code></pre>
<p>The <code>_updateRankingStatsNoTransaction</code> function looks like this:</p>
<pre><code>Future<void> _updateRankingStatsNoTransaction(
GameResult gameResult, // contain game result data
String collection, // which collection to update
DateTime date, // which date
// a function to parse game result to ranking map for a player or pair.
// hence I have two such parser functions, one for player, one for pair.
Map<String, Map<String, int>> Function(
GameResult, Map<String, Map<String, int>>)
rankingParser) async {
// firstly check whether there is a document already for the given group
// and date.
// if not, create a new document and insert the parsed ranking stats.
// if yes, update the existing document to store the updated ranking stats.
}
</code></pre>
<p>My questions:</p>
<ol>
<li><p>Obviously I want to know whether there is a better way of doing all this. I feel like there needs a balance between making querying data and writing data relatively easy. Some way of designing the data structure could lead to querying easier but writing harder, or writing easier but querying harder.</p></li>
<li><p>Would a relational or graph database suit this kind of problem better? I did try to use SQL to model this before though can't find the code anymore. But I did have to use a lot of long nested queries/views/store procedures, which feels ugly.</p></li>
</ol>
| [] | [
{
"body": "<p>Overall, I would do something similar as you do now. Since firestore is not good at query at all, I agree we should write harder.</p>\n\n<p>If your query is really complicated and need to be in relational-like, I guess the answer is SQL-like solution. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T20:52:23.203",
"Id": "211642",
"ParentId": "211624",
"Score": "0"
}
},
{
"body": "<p>Okay, I don't think you need 8 root level stats collections. Instead one stats collection and create those 8 as sub collections. Keep in mind that you can't query across the sub collections. (Anyway you can't query across the root level collections too. So, you are not losing anything)</p>\n\n<pre><code>stats\n playerdaily\n {\n date : '2019-01-14',\n groupId : 'abcd',\n Bob : {\n played : 1,\n won : 0,\n },\n John : {\n played : 1,\n won : 0\n },\n Tony : {\n played : 1,\n won : 1\n },\n Mike : {\n played : 1,\n won: 1\n }\n playermonthly\n ...\n playerannually\n playeralltime\n pairdaily\n pairmonthly\n pairannually\n pairalltime\n</code></pre>\n\n<pre><code>games\n gameid {\n date : '2019-01-14',\n groupId : 'abcd',\n player1 : 'Bob',\n player2 : 'John', // can be null\n player3 : 'Tony',\n player4 : 'Mike', // can be null\n score1 : 15,\n score2 : 21\n}\n</code></pre>\n\n<p>Write a cloud function with create trigger. Every time a new game added, update these stats sub collection. Firestore is not great in aggregating. You have to take care of that. </p>\n\n<p>I don't see why you need a graph database for this. If you need to find relationship between players and games, then it could be useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T14:01:22.710",
"Id": "416131",
"Score": "1",
"body": "Thanks for this. Maybe I am not understanding this but using one root collection with 8 sub-collection doesn't fundamentally change how this is done, does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T21:11:12.317",
"Id": "416195",
"Score": "0",
"body": "Exactly. It doesn't change fundamentally how you are doing, but gives you a better schema structure. I felt that was the question (how to improve the data structure)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T18:26:30.863",
"Id": "215148",
"ParentId": "211624",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T14:41:57.050",
"Id": "211624",
"Score": "0",
"Tags": [
"database",
"firebase",
"nosql",
"dart"
],
"Title": "NoSQL data model design for players in a game"
} | 211624 |
<p>It's a simple app that uses a public API to display data. It works as is, but I'm seeing a lot of spaghetti code that my limited experience can't fix on its own.</p>
<pre><code>import React, { Component } from "react";
import Spinner from "./components/common/Spinner";
import "../src/App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoading: false
};
}
componentDidMount() {
const urlParams = new URLSearchParams(window.location.search);
const city = urlParams.get("city");
fetch(`http://opentable.herokuapp.com/api/restaurants?city=${city}`)
.then(res => res.json())
.then(json => {
this.setState({
isLoading: true,
items: json
});
});
}
render() {
const { isLoading, items } = this.state;
let content = <h2>No Data</h2>;
if (!items.restaurants || items.restaurants === []) {
content = <h2>No Data</h2>;
} else if (items.restaurants.length !== 0) {
console.log(items);
let itemsToArray = Object.values(items.restaurants);
content = (
<div className="App">
<div className="row">
<div className="col-md-3">
{itemsToArray.map(item => (
<li key={item.id} style={{ listStyleType: "none" }}>
<a
href={item.reserve_url}
style={{ color: "red" }}
target="_blank"
>
{item.name}
</a>{" "}
| <span style={{ fontStyle: "italic" }}>{item.address}</span>{" "}
| Price rating:{" "}
<span style={{ color: "red" }}>{item.price}</span>
</li>
))}
</div>
</div>
</div>
);
}
return !isLoading ? (
<div>
<Spinner />
</div>
) : (
<React.Fragment>
<div className="row">
<div className="col-md-6">
<div>{content}</div>
</div>
</div>
</React.Fragment>
);
}
}
export default App;
</code></pre>
| [] | [
{
"body": "<p>I can think of mutliple ways to improve this code.</p>\n\n<p>First, error handling. In your case, not receiving data from your API call may cause your program to crash.</p>\n\n<p>You will have to add an error variable in your state :</p>\n\n<pre><code>this.state = {\n items: [],\n isLoading: true,\n error: ''\n};\n</code></pre>\n\n<p>And add a <code>.catch</code> at the end of your <code>fetch</code> function (or use the new <code>async/await</code> syntax surrounded by a <code>try/catch</code> block).</p>\n\n<p>You should also put your response formatting here instead of the rendering function, to avoid reformatting your data everytime your component is rerendered :</p>\n\n<pre><code>fetch(`http://opentable.herokuapp.com/api/restaurants?city=${city}`)\n .then(res => res.json())\n .then(json => {\n this.setState({\n isLoading: false,\n items: Object.values(json.restaurants) //Data formatting\n });\n })\n .catch(error =>{\n this.setState({\n isLoading: false,\n error // Sends the error object (or message, I am not sure about the exact syntax)\n });\n });\n</code></pre>\n\n<p>I also noticed that you set your <code>isLoading</code> state to <code>true</code> when you finished loading and to <code>false</code> in your initial state so I reversed it.</p>\n\n<p>Now, the rendering.</p>\n\n<p>JSX allows you to put <a href=\"https://reactjs.org/docs/conditional-rendering.html\" rel=\"nofollow noreferrer\">conditions inside your HTML</a>, making the syntax of your render way more readable and avoid code duplication :</p>\n\n<pre><code>render() {\n const { isLoading, items, error } = this.state;\n\n return (\n <div className=\"row\">\n <div className=\"col-md-6\">\n <div className=\"App\">\n <div className=\"row\">\n <div className=\"col-md-3\">\n {isLoading && <Spinner />}\n {error && <div>Error : {error}</div>}\n {!isLoading && !items.length && <h2>No Data</h2>}\n <ul> // Did you forget this node ?\n {items.map(({ id, reserve_url, address, price, name }) => //Won't do anything if the items array is empty\n <li key={id} style={{ listStyleType: \"none\" }}>\n <a\n href={reserve_url}\n style={{ color: \"red\" }}\n target=\"_blank\"\n >\n {name}\n </a>{\" \"}\n | <span style={{ fontStyle: \"italic\" }}>{address}</span>{\" \"}\n | Price rating:{\" \"}\n <span style={{ color: \"red\" }}>{price}</span>\n </li>\n )}\n </ul>\n </div>\n </div>\n </div>\n </div>\n </div>\n )\n}\n</code></pre>\n\n<p>I also deconstructed your parameters in the <code>map</code> function.</p>\n\n<p>Working example :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class App extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n items: [],\n isLoading: true,\n error: ''\n };\n }\n\n componentDidMount() {\n const urlParams = new URLSearchParams(window.location.search);\n const city = urlParams.get(\"city\");\n\n fetch(`http://opentable.herokuapp.com/api/restaurants?city=London`) // Hard coded London\n .then(res => res.json())\n .then(json => {\n setTimeout(() => { //Just to see the loading element / spinner\n this.setState({\n isLoading: false,\n items: Object.values(json.restaurants)\n });\n }, 1500)\n })\n .catch(error =>{\n this.setState({\n isLoading: false,\n error\n });\n });\n }\n\n render() {\n const { isLoading, items, error } = this.state;\n\n return (\n <div className=\"row\">\n <div className=\"col-md-6\">\n <div className=\"App\">\n <div className=\"row\">\n <div className=\"col-md-3\">\n {isLoading && <div>Loading...</div>}\n {error && <div>Error : {error}</div>}\n {!isLoading && !items.length && <h2>No Data</h2>}\n <ul>\n {items.map(({ id, reserve_url, address, price, name }) =>\n <li key={id} style={{ listStyleType: \"none\" }}>\n <a\n href={reserve_url}\n style={{ color: \"red\" }}\n target=\"_blank\"\n >\n {name}\n </a>{\" \"}\n | <span style={{ fontStyle: \"italic\" }}>{address}</span>{\" \"}\n | Price rating:{\" \"}\n <span style={{ color: \"red\" }}>{price}</span>\n </li>\n )}\n </ul>\n </div>\n </div>\n </div>\n </div>\n </div>\n )\n }\n}\n\nReactDOM.render(<App/>, document.getElementById('root'))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js\"></script>\n<div id='root'/></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T16:50:43.583",
"Id": "409246",
"Score": "1",
"body": "This isn't tagged as an interview question, so what do recruiters have to do with anything?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T16:54:21.950",
"Id": "409247",
"Score": "0",
"body": "Weird, I remembered seeing it somewhere in the question, I'll remove it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T16:11:09.650",
"Id": "211629",
"ParentId": "211626",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T15:42:48.340",
"Id": "211626",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "Using a public API to display data"
} | 211626 |
<p>As an exercise, I wrote a program to decrypt a PDF file. The only thing that is known about the encryption password is that it is a single English word (all capital or lowercase).</p>
<p>The program uses a <a href="https://ufile.io/ja186" rel="nofollow noreferrer">dictionary file</a> containing over 45000 words to unlock the file. It looks like this:</p>
<p><strong>dictionary.txt</strong></p>
<pre><code>AARHUS
AARON
ABABA
ABACK
ABAFT
ABANDON
ABANDONED
ABANDONING
ABANDONMENT
ABANDONS
ABASE
ABASED
ABASEMENT
ABASEMENTS
ABASES
ABASH
ABASHED
ABASHES
⋮
ZEROTH
ZEST
ZEUS
ZIEGFELD
ZIEGFELDS
ZIEGLER
ZIGGY
ZIGZAG
ZILLIONS
ZIMMERMAN
ZINC
ZION
ZIONISM
ZIONIST
ZIONISTS
ZIONS
ZODIAC
ZOE
ZOMBA
ZONAL
ZONALLY
ZONE
ZONED
ZONES
ZONING
ZOO
ZOOLOGICAL
ZOOLOGICALLY
ZOOM
ZOOMS
ZOOS
ZORN
ZOROASTER
ZOROASTRIAN
ZULU
ZULUS
ZURICH
</code></pre>
<p><strong>pdf_password_breaker</strong></p>
<pre><code>"""
Brute force password breaker using a dictionary containing
English words.
"""
import sys
import PyPDF2
from pathlib import Path
def get_filename_from_user() -> Path:
"""Asks for a path from the User"""
while True:
filename: str = input("Enter filename in folder of script:")
path: Path = Path(sys.path[0], filename)
if path.is_file():
return path.as_posix()
print("File doesn't exist\n")
def decrypt(pdf_filename: Path, password: str) -> bool:
"""
Try to decrypt a file. If not successful a false is returned.
If the file passed is not encrypted also a false is passed
"""
with open(pdf_filename, 'rb') as pdf_file:
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
pdf_reader.decrypt(password)
pdf_writer = PyPDF2.PdfFileWriter()
try:
for page_number in range(pdf_reader.numPages):
pdf_writer.addPage(pdf_reader.getPage(page_number))
except PyPDF2.utils.PdfReadError:
return False
new_name: str = pdf_filename.stem + "_decrypted.pdf"
filename_decrypted = pdf_filename.parent / new_name
with open(filename_decrypted, 'wb') as pdf_file_decrypted:
pdf_writer.write(pdf_file_decrypted)
return True
def break_encryption(pdf_filename: Path, dictionary_filename: str) -> bool:
"""Try's out words from a dictionary to break encryption"""
with open(dictionary_filename, 'r') as dictionary_file:
keyword: str = dictionary_file.readline().strip()
if decrypt(pdf_filename, keyword):
return keyword
if decrypt(pdf_filename, keyword.lower()):
return keyword.lower()
while keyword:
keyword = dictionary_file.readline().strip()
if decrypt(pdf_filename, keyword):
return keyword
if decrypt(pdf_filename, keyword.lower()):
return keyword.lower()
return None
def pdf_password_breaker():
"""main loop"""
filename: Path = get_filename_from_user()
password: str = break_encryption(filename, "dictionary.txt")
if password:
print("File unlocked. Password was:" + password)
return
print("File could not be unlocked")
if __name__ == "__main__":
pdf_password_breaker()
</code></pre>
<p>I tried a file with a simple password like "hello". It works but it takes a lot of time until it reaches the "hello" in the file.</p>
<p>I wonder if theres a way to improve the speed, or any other aspect of the code.</p>
| [] | [
{
"body": "<p>Looking at the documentation of <a href=\"https://pythonhosted.org/PyPDF2/PdfFileReader.html#PyPDF2.PdfFileReader.decrypt\" rel=\"noreferrer\">PdfFileReader.decrypt</a> It states that it return 0 if the file fails or 1 if it succeeds.</p>\n\n<p>You can also use isEncrypted to check if the file was encrypted in the first place.</p>\n\n<p>So you can turn the loop around. First open the pdf file see if it was encrypted at all and if so try to call <code>decrypt</code> with every password in your dictionary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T23:38:34.153",
"Id": "409283",
"Score": "1",
"body": "And in doing that, only open the PDF file once - opening it twice for every password is a huge slow down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:00:59.777",
"Id": "409378",
"Score": "0",
"body": "i tryed that approach. it got quite a bit faster. but to crack hello it still takes quite some time"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T17:31:57.543",
"Id": "211633",
"ParentId": "211632",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T17:25:01.250",
"Id": "211632",
"Score": "7",
"Tags": [
"python",
"performance",
"beginner",
"pdf"
],
"Title": "Open encrypted PDF file by trying passwords from a word list"
} | 211632 |
<p>I would like to ask how I can make my code more simple and effective. I know that this code can be 100% better. I am supposed to load number for each array and then take the 2 arrays (4*3 and 3*4) and multiply them into 3*3 array.</p>
<p>The main point is making the<code>scanf_</code>s for both <code>int a</code> and <code>int b</code> in one "piece of code."</p>
<pre><code>#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a[3][4];
int b[4][3];
int c[3][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
for (int j = 0; j != 4; j++)
{
for (int l = 0; l != 4; l++)
{
cout << "Zadej a[" << j << "," << l << "]: ";
scanf_s("%d", &a[j][l]);
}
}
for (int j = 0; j != 4; j++)
{
for (int l = 0; l != 4; l++)
{
cout << "Zadej b[" << j << "," << l << "]: ";
scanf_s("%d", &b[j][l]);
}
}
for (int j = 0; j != 3; j++)
{
for (int l = 0; l != 3; l++)
{
;
printf(" |%d| ", c[j][l] += a[j][l] * b[j][l]);
}
printf("\n");
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T17:56:00.180",
"Id": "409252",
"Score": "2",
"body": "_\"Is the code working the right way ?\"_ It's you who's in charge to ensure that, before asking for a review here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T18:01:05.680",
"Id": "409253",
"Score": "0",
"body": "Don't take me the wrong way, _it is working_ but I have never done anything with matrixes yet so I am not sure if I'm counting it the right way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T18:02:20.977",
"Id": "409254",
"Score": "4",
"body": "Write appropriate test cases first to the best of your knowledge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T18:06:40.117",
"Id": "409255",
"Score": "0",
"body": "@πάντα ῥεῖ I am absolutely certain that it works the right way so if you could kindly help me with the other two points I would be glad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:49:26.217",
"Id": "409266",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:50:24.170",
"Id": "409267",
"Score": "1",
"body": "Your new code was barely an improvement compared to the old code. Please wait a while longer, more answers might be incoming. Feel free to take another good look at it yourself as well. Should you write a piece that's definitely improved, write a follow-up question linking back to this one for bonus context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:55:58.810",
"Id": "409268",
"Score": "0",
"body": "@PatrikŠoukal in [that revision](https://codereview.stackexchange.com/revisions/211634/4) you added a question... you could put that question in [a comment](https://meta.stackexchange.com/a/19757/341145) on Toby's answer (though won't be able to put the updated code block in, since it would be too long)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T02:58:21.660",
"Id": "409291",
"Score": "0",
"body": "That is not matrix multiplication. One good hint that you’re not doing it right is that you don’t use all of the elements of `a` and `b`. Look for “matrix multiplication” on Wikipedia, I’m sure you can find an algorithm there for how you should compute this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T03:01:20.707",
"Id": "409292",
"Score": "2",
"body": "...Sorry, Wikipedia was bad advice, that is terribly obtusely written. [Here is a better explanation](https://www.mathsisfun.com/algebra/matrix-multiplying.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T06:16:37.070",
"Id": "409299",
"Score": "0",
"body": "@CrisLuengo Thanks for pointing that out, honestly I didn't notice that I need to use one more for loop. The code should look like this: ‘for (j = 0, i < 3, i++)\n for (l = 0, j < 3, j++)\n C[i][j] = 0\n for (k = 0, k < 4, k++)\n C[j][l] += A[j][k] * B[k][l]‘"
}
] | [
{
"body": "<h1>Don't put everything into one big <code>main()</code></h1>\n\n<p>If you can separate out the reading of inputs and writing of results from the actual multiplications, then it will be easier to test the multiplication code separately.</p>\n\n<h1>Avoid non-standard libraries</h1>\n\n<p>Here we have <code>\"stdafx.h\"</code> and <code>scanf_s</code> that aren't part of standard C++. Ditch those and use the standard facilities (e.g. <code>std::cin >> a[j][l]</code>).</p>\n\n<h1>Include what you use</h1>\n\n<p>We don't seem to use <code><cmath></code> anywhere, so let's drop that. We'll need <code><cstdio></code> for <code>std::printf()</code> - or switch to C++ style output using <code><iostream></code>.</p>\n\n<h1>Avoid using the whole <code>std</code> namespace</h1>\n\n<p>The <code>std</code> namespace isn't one of the few that's designed to be imported wholesale like that, and there's potential for name conflicts when moving to a new standards version. Specify just the names you need, or just get used to writing <code>std::</code> - it's intentionally very short.</p>\n\n<h1>Use C++ collections</h1>\n\n<p>It's easier to work with the C++ collection types such as <code>std::array</code> or <code>std::vector</code> than with raw (C-style) arrays (which decay to pointers when passed as function arguments).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:58:18.817",
"Id": "409269",
"Score": "0",
"body": "So I edited the code a bit but now it posts an error: \"no operator \"<<\" matches these operands\". Also now that I removed the [] brackets how am I supposed to change the x/y the same way I did before?\n\n`std::array<int, 3> a;\n std::array<int, 4> b;\n std::array<int, 3> c;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T18:13:53.613",
"Id": "211637",
"ParentId": "211634",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T17:54:04.930",
"Id": "211634",
"Score": "0",
"Tags": [
"c++",
"matrix"
],
"Title": "Multiplying two arrays"
} | 211634 |
<p>I've tried solving <a href="https://i.stack.imgur.com/Gzkb1.png" rel="nofollow noreferrer">the following HackerRank question</a>:</p>
<blockquote>
<p>Write a function <code>blur_image()</code> that takes as a parameter an image in the form of a nested list <code>A</code> and blurs it by averaging each pixel value with four of its neighboring pixels (Top, Bottom, Right, and Left). Note: not all of the neighbors are available in boundary cases. You have to write suitable conditions accordingly.</p>
</blockquote>
<p>My Solution:</p>
<pre><code>import ast
A = input()
A = ast.literal_eval(A)
def blur_image(a):
result = []
for i in range(len(a)):
row = []
for j in range(len(a[i])):
total, count = a[i][j], 1
if i + 1 < len(a): total, count = total + a[i+1][j], count + 1
if j + 1 < len(a[i]): total, count = total + a[i][j+1], count + 1
if i - 1 > -1: total, count = total + a[i-1][j], count + 1
if j - 1 > -1: total, count = total + a[i][j-1], count + 1
row.append(round(total/count, 2))
result.append(row)
return result
print(blur_image(A))
</code></pre>
<p>I would appreciate any suggestions and advice you can give me to improve this solution. Please note that my focus is to solve this without using any modules.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T02:04:46.963",
"Id": "409287",
"Score": "0",
"body": "Do you care for speed at the expense of longer code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T02:18:43.010",
"Id": "409288",
"Score": "0",
"body": "If you want speed, look up summed area tables."
}
] | [
{
"body": "<p>First, I think this code arguably <em>abuses</em> tuple destructuring to declare and reassign variables. Declaring multiple variables on a line generally hurts readability, just to save a line/some keystrokes. I would write everything out fully, even if that comes with the cost of verbosity. I'd also space it out a bit:</p>\n\n<pre><code>def my_blur_image1(a):\n result = []\n for i in range(len(a)):\n row = []\n for j in range(len(a[i])):\n total = a[i][j]\n count = 1\n if i + 1 < len(a):\n total += a[i+1][j]\n count += 1\n\n if j + 1 < len(a[i]):\n total += a[i][j+1]\n count += 1\n\n if i - 1 > -1:\n total += a[i-1][j]\n count += 1\n\n if j - 1 > -1:\n total += a[i][j-1]\n count += 1\n\n row.append(round(total/count, 2))\n\n result.append(row)\n\n return result\n</code></pre>\n\n<hr>\n\n<p>Twice, you have something along the lines of</p>\n\n<pre><code>lst = [] # Create a list\nfor i in range(len(a)):\n res = # Calculate some result\n lst.append(res)\n</code></pre>\n\n<p>I think the logic could be broken up, and could make use of some list comprehensions. This is basically the scenario that list comprehensions (and <code>map</code>) are intended for. Iterating over a list to produce a new list is a <em>very</em> common operation.</p>\n\n<p>I'm not <em>necessarily</em> recommending this way, but it does show an alternative, more functional way of approaching the problem. I'll say that my way ended up a fair bit slower than yours. On my machine, yours takes roughly 14 seconds for a 2000x2000 matrix, while my version takes 25 seconds unfortunately. You didn't tag performance though :D</p>\n\n<pre><code># Returns whether or not i,j is inbound for a given a matrix\ndef inbounds(i, j, a):\n return 0 <= i < len(a) and \\\n 0 <= j < len(a[i])\n\n# Returns the inbound pixel values on and surrounding the given point\ndef inbound_pixels_around(i, j, a):\n # I figured it was best to hard-code the indices instead of using several \"if\"s like you had done\n # That way, I can make use of looping to reduce some duplication\n # If diagonal pixels were included, this could be generated by another comprehension instead\n indices = [(i, j), (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]\n\n # Iterate over the indices.\n # Remove the ones that are out of bounds, and use the inbound ones to index the list\n return [a[i][j] for (i, j) in indices if inbounds(i, j, a)]\n\ndef my_blur_image2(a):\n # A 3D-array. Each pixel has been replaced by a list of inbound neighbor values\n inbound_neigh_rows = [[inbound_pixels_around(i, j, a) for j in range(len(a[i]))]\n for i in range(len(a))]\n\n # Then iterate ever each set of neighbors, and divide the sum of the neighbors by their length\n # This does away with needing an explicit \"count\" variable\n return [[sum(neighs) / len(neighs) for neighs in row]\n for row in inbound_neigh_rows]\n</code></pre>\n\n<p>I'm making fairly extensive use of list comprehensions here. I'm using them to filter out non-inbound cells in <code>inbound_pixels_around</code> using <code>inbounds</code>, and to generate neighbors and their average values in <code>my_blur_image2</code>.</p>\n\n<pre><code>test_data = [[1, 2, 3],\n [4, 5, 6],\n [7, 8 ,9]]\n\nprint(blur_image(test_data))\nprint(my_blur_image1(test_data))\nprint(my_blur_image2(test_data))\n\n[[2.33, 2.75, 3.67], [4.25, 5.0, 5.75], [6.33, 7.25, 7.67]]\n[[2.33, 2.75, 3.67], [4.25, 5.0, 5.75], [6.33, 7.25, 7.67]]\n[[2.3333333333333335, 2.75, 3.6666666666666665], [4.25, 5.0, 5.75], [6.333333333333333, 7.25, 7.666666666666667]]\n</code></pre>\n\n<hr>\n\n<p>Updated to make use of comparison chaining. Thanks @Mathias.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T08:12:49.843",
"Id": "409309",
"Score": "0",
"body": "You can simplify `inbounds` by using extended comparison syntax: `0 <= i < len(a) and 0 <= j < len(a[i])`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:19:35.773",
"Id": "409340",
"Score": "0",
"body": "@MathiasEttinger Oh yes, thanks. Forgot Python had that. I'll need to update that on a bit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T00:41:47.063",
"Id": "211651",
"ParentId": "211636",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T18:13:38.923",
"Id": "211636",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"matrix",
"signal-processing"
],
"Title": "Blurring a given image using moving average in Python 3"
} | 211636 |
<p>I recently had to repeatedly iterate over an array but increment the index to start from each time. Since this is quite cumbersome in comparison to a normal for loop I made a small template function that does this for me:</p>
<pre><code>#include <algorithm>
#include <iostream>
template<typename TSize, typename TFunc>
void for_start(const TSize start, const TSize size, TFunc&& fn)
{
for(TSize c{}, i{c + start}; c < size; ++c, ++i)
{
if(i >= size)
i = 0;
fn(i);
}
}
template<typename TRAIter, typename TFunc>
void for_start(TRAIter start, TRAIter begin, TRAIter end, TFunc&& fn)
{
for(TRAIter c{begin}, i{c + std::distance(begin, start)}; c != end; ++i, ++c)
{
if(i == end)
i = begin;
fn(i);
}
}
// usage
int main()
{
const unsigned ARR_SIZE{10};
int arr[ARR_SIZE]{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
};
for_start(5u, ARR_SIZE, [arr](unsigned i)
{
std::cout << arr[i] << ' ';
});
std::cout << '\n';
for_start(std::begin(arr) + 5, std::begin(arr), std::end(arr), [](const int* i)
{
std::cout << *i << ' ';
});
}
// prints:
// 5 6 7 8 9 0 1 2 3 4
// 5 6 7 8 9 0 1 2 3 4
</code></pre>
<p>I'd like to get some feedback on things like usability (function name, order of parameters) and reuseability. Note that I'd like to use this function with signed & unsigned integers.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:17:31.153",
"Id": "409264",
"Score": "0",
"body": "If you weren't constrained to C++11, I'd have suggested you look into `std::range`, which has been voted in to C++20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:18:52.763",
"Id": "409265",
"Score": "0",
"body": "@TobySpeight, this is not my birthday, but thank you for the gift. Though googling for it didn't yield anything useful yet."
}
] | [
{
"body": "<ul>\n<li><p>There is no reason to initialize <code>i</code> as <code>{c + std::distance(begin, start)}</code>. Upon such initialization you are guaranteed that <code>i == start</code>. A much simpler <code>i{start}</code> suffices.</p></li>\n<li><p>Testing for <code>i == size</code>, or <code>i == end</code> inside the loop, as well as tracking two iterators, feels wasteful. Consider splitting the loop into two, e.g:</p>\n\n<pre><code> for (i = start; i != end; ++i) {\n fn(i);\n }\n\n for (i = begin; i != start; ++i) {\n fn(i);\n }\n</code></pre></li>\n<li><p>I am not sure that <code>for_start</code> is a good name. I am also not sure what name would be good. <code>iterate_rotated</code> perhaps?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:02:44.340",
"Id": "409367",
"Score": "0",
"body": "The idea to use 2 seperate loops didn't even cross my mind... Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T20:45:55.487",
"Id": "211641",
"ParentId": "211639",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "211641",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:15:09.317",
"Id": "211639",
"Score": "2",
"Tags": [
"c++",
"c++11",
"template"
],
"Title": "Loop over whole array starting from any index"
} | 211639 |
<p>In my program I am transferring image files continuously through QTCPSocket for each frame I am creating new connection which I believe causes the performance problems. But I couldn't transform my code into single connection one. Everything works fine I can transfer images continuously but frame rate seems lower than I expected. I send 24 frames per second and recieve roughly 13 frames.</p>
<p>How can I improve performance of my code ?</p>
<p>Here is my code:</p>
<p><strong>tcpsender.cpp</strong></p>
<pre><code>#include "tcpsender.h"
#include "ui_tcpsender.h"
#include <QtWidgets>
#include <QtNetwork>
#include <QtCore>
#include <QDebug>
#include <QBuffer>
#define XRES 640
#define YRES 480
TCPSender::TCPSender(QWidget *parent) :
QWidget(parent),
ui(new Ui::TCPSender)
{
ui->setupUi(this);
statusLabel = new QLabel(tr("Ready to send frames on port 6667"));
statusLabel->setWordWrap(true);
startButton = new QPushButton(tr("&Start"));
auto quitButton = new QPushButton(tr("&Quit"));
auto buttonBox = new QDialogButtonBox;
buttonBox->addButton(startButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
socket = new QTcpSocket(this);
connect(startButton, &QPushButton::clicked, this, &TCPSender::startConnection);
connect(quitButton, &QPushButton::clicked, this, &TCPSender::close);
connect(socket, SIGNAL(connected()), SLOT(startSending()));
connect(&timer, &QTimer::timeout, this, &TCPSender::sendFrame);
auto mainLayout = new QVBoxLayout;
mainLayout->addWidget(statusLabel);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
setWindowTitle(tr("Broadcast Sender"));
camera = new Camera("/dev/video0", XRES, YRES);
time = QTime::currentTime();
}
TCPSender::~TCPSender()
{
delete ui;
}
void TCPSender::startConnection()
{
if (socket->state() == QAbstractSocket::UnconnectedState)
{
QString ip = ui->lineEdit->text();
socket->connectToHost(ip, 6667, QIODevice::WriteOnly);
}
else
{
socket->disconnectFromHost();
}
}
void TCPSender::startSending()
{
startButton->setEnabled(false);
timer.start(1000/24);
}
void TCPSender::sendFrame()
{
if(socket->state()==QAbstractSocket::ConnectedState){
auto frame = camera->frame();
image = new QImage(frame.data,XRES,YRES,QImage::Format_RGB888);
QImage im = image->convertToFormat(QImage::Format_Grayscale8);
QByteArray ba;
QBuffer buffer(&ba);
im.save(&buffer,"BMP");
socket->write(ba);
int speed = time.msecsTo(QTime::currentTime());
time = QTime::currentTime();
speed = 1000*300/speed;
ui->label->setText(QString("%1 kb/s").arg(speed));
delete image;
}
startConnection();
}
</code></pre>
<p><strong>receiver.cpp</strong></p>
<pre><code> #include "reciever.h"
#include <QBuffer>
#include <QTcpSocket>
#include <QImage>
#include <QDebug>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <unistd.h>
#define XRES 640
#define YRES 480
#define SIZE 640*480*3
Reciever::Reciever(QObject* parent): QTcpServer(parent)
{
connect(this, SIGNAL(newConnection()), this, SLOT(addConnection()));
}
void Reciever::addConnection()
{
QTcpSocket* connection = nextPendingConnection();
connections.append(connection);
QBuffer* buffer = new QBuffer(this);
buffer->open(QIODevice::ReadWrite);
buffers.insert(connection, buffer);
connect(connection, SIGNAL(disconnected()), SLOT(removeConnection()));
}
void Reciever::removeConnection()
{
receiveImage();
QTcpSocket *socket = static_cast<QTcpSocket*>(sender());
QBuffer* buffer = buffers.take(socket);
buffer->close();
buffer->deleteLater();
connections.removeAll(socket);
socket->deleteLater();
}
void Reciever::receiveImage()
{
QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
QBuffer* buffer = buffers.value(socket);
qint64 bytes = buffer->write(socket->readAll());
emit sendBuffer(buffer,bytes);
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:33:56.673",
"Id": "211640",
"Score": "1",
"Tags": [
"c++",
"tcp",
"qt"
],
"Title": "Transfering Image Data with QTCPSocket"
} | 211640 |
<p>The <code>DocumentClient</code> is an object that accesses <code>CosmosDb</code>, but Microsoft recommends its kept as a <code>Singleton</code> class. I'm relying on <code>System.Lazy</code> to ensure thread safety.</p>
<p>In addition, I want to be able to overwrite my <code>DocumentClient</code> when I need to test. Is this correct?</p>
<pre><code>public sealed class DocumentClientSingleton
{
public static IDocumentClient GetInstance()
{
return _lazy.Value;
}
/// <summary>
/// Only use this for testing!
/// </summary>
/// <returns></returns>
public static IDocumentClient SetInstanceForTesting(IDocumentClient client)
{
_lazy = new Lazy<IDocumentClient>(() => client );
return _lazy.Value;
}
private static Lazy<IDocumentClient> _lazy =
new Lazy<IDocumentClient>(InstantiateDocument);
private static IDocumentClient InstantiateDocument()
{
return new DocumentClient(
new Uri(ConfigurationManager.AppSettings["endpoint"]),
ConfigurationManager.AppSettings["authKey"],
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp
}
);
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>This answer only has one tiny section (<code>IDisposable</code>) that I feel is an appropriate kind of answer for Code Review. The rest is more suitable as a StackOverflow answer (since it dives into the specifics of the <code>DocumentClient</code> class). I apologize in advance, and if I should move my answer or edit it in anyway, please feel free to advise me in the comments section.</p>\n</blockquote>\n\n<h2>The <code>DocumentClient</code>class is already thread-safe.</h2>\n\n<p>From what I can gather reading the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.client.documentclient?redirectedfrom=MSDN&view=azure-dotnet#remarks\" rel=\"nofollow noreferrer\">latest documentation</a> on the <code>DocumentClient</code> class, is that it is already inherently thread-safe. Provided that this remains true, your class wrapper is obsolete.</p>\n\n<p>It seems that this confusion was also asked as a question over at <a href=\"https://stackoverflow.com/q/39513803/3645638\">StackOverflow</a></p>\n\n<hr>\n\n<h2>Microsoft's recommendation of using <code>DocumentClient</code> as a singleton</h2>\n\n<blockquote>\n <p>If you can draw a parallel to how Microsoft recommends usage of the <code>HttpClient</code> then you might have a better idea of what I mean from this point onwards.</p>\n</blockquote>\n\n<p>Microsoft recommends that you use a <strong>single instance*</strong> per application. (again, think of <code>HttpClient</code>)</p>\n\n<p>In the case of a web application using ASP.NET this usually comes in the form of dependency injection via declaring the lifetime of the class to <code>Singleton</code>.</p>\n\n<pre><code>// dependency injection for ASP.NET\nservices.AddSingleton(myDocumentClientInstance);\n</code></pre>\n\n<p>This might be the root cause of your misunderstanding. The use of the word \"singleton\" from the article you probably read, is actually an ASP.NET convention for specifying a lifetime of the instance and also ensuring that only a single (shared) instance is used across your entire web application.</p>\n\n<p>This doesn't mean that implementing the <code>DocumentClient</code> as a singleton class is wrong.</p>\n\n<p>In such a case, a <strong>static instance</strong> (like you have done) could be the answer. But you're going to get a group of developers that will throw fists in the air at you for making the code difficult-to-impossible to unit test if you do so... You have been warned!</p>\n\n<hr>\n\n<h2>The <code>DocumentClient</code> class implements <code>IDisposable</code>.</h2>\n\n<p>Based on your code it will become quite a complex task of making sure that the instance is properly disposed.</p>\n\n<p>The recommended way to handle an object that implements the <code>IDisposable</code> interface is by using the the <code>using</code> block.</p>\n\n<pre><code>using (IDocumentClient client = new DocumentClient(new Uri(\"endpoint\"), \"authKey\"))\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<h2>Special cases</h2>\n\n<p>To summarize with a special case, which could hopefully shine some additional light why your implementation will be troublesome as a true singleton.</p>\n\n<p>There are some special cases for using more than one instance. In particular, if you have multiple CosmosDb accounts, then you should actually use one instance for each account. You can read about that <a href=\"https://github.com/Azure/azure-cosmos-dotnet-v2/issues/289#issuecomment-310498742\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<blockquote>\n <p>Note: The parallel to <code>HttpClient</code> does not work here, since we are creating multiple instances on purpose.</p>\n</blockquote>\n\n<p>Your particular implementation will fall short when you have a scenario with multiple CosmosDb accounts. So please keep that in mind.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-04T13:44:59.497",
"Id": "433209",
"Score": "0",
"body": "What to do for multiple CosmosDb configurations?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T03:21:59.133",
"Id": "211653",
"ParentId": "211643",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T20:59:30.783",
"Id": "211643",
"Score": "1",
"Tags": [
"c#",
"singleton",
"lazy"
],
"Title": "Singleton class to contain a DocumentClient instance, that can be overridden for testing"
} | 211643 |
<p>I have a text based Tic-Tac-Toe game with a simple AI element that will take winning moves and block losing moves. The one piece of criticism I received was that I was 'hard coding' too much. I can see this, for example, in <code>check_computer_win</code>. How can I use a dictionary to cut down on hard coding? What are some of the best ways I can solve my repetition problem?</p>
<pre><code>#! python
""" This my Tic Tac Toe game with python.
2019-01-10
"""
import random
import sys
board = [1,2,3,4,5,6,7,8,9]
open_boxes = 9
human_letter = ''
opp_letter = ''
winner = False
can_block = False
def choose_letter():
global human_letter
global opp_letter
human_letter = input('Please choose "x" or "o": ').lower()
if human_letter == 'x':
opp_letter = 'o'
elif human_letter == 'o':
opp_letter = 'x'
else:
print('Please choose again.')
choose_letter()
def show_board():
print (board[0], '|', board[1], '|', board[2])
print ("----------")
print (board[3], '|', board[4], '|', board[5])
print ("----------")
print (board[6], '|', board[7], '|', board[8])
print (" ")
def checkLine(char, first, second, third):
if board[first] == char and board[second] == char and board[third] == char:
return True
def checkAll(char):
if checkLine(char,0,1,2):
return True
if checkLine(char,3,4,5):
return True
if checkLine(char,6,7,8):
return True
if checkLine(char,0,3,6):
return True
if checkLine(char,1,4,7):
return True
if checkLine(char,2,5,8):
return True
if checkLine(char,0,4,8):
return True
if checkLine(char,2,4,6):
return True
def computer_move():
global open_boxes
if open_boxes > 0:
check_computer_win()
if not winner:
block_human_win()
if not can_block:
opp_move = random.randint(0,8)
if board[opp_move] != 'o' and board[opp_move] != 'x':
open_boxes -= 1
board[opp_move] = opp_letter
print('Computer\'s turn')
print('Computer is thinking...')
print('\n')
show_board()
else:
computer_move()
else:
print('--DRAW--')
play_again()
def check_computer_win():
#check for a top horizontal win
if board[0] == opp_letter and board[1] == opp_letter:
if board[2] != human_letter:
board[2] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[0] == opp_letter and board[2] == opp_letter:
if board[1] != human_letter:
board[1] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[1] == opp_letter and board[2] == opp_letter:
if board[0] != human_letter:
board[0] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a middle horizontal win
if board[3] == opp_letter and board[4] == opp_letter:
if board[5] != human_letter:
board[5] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[3] == opp_letter and board[5] == opp_letter:
if board[4] != human_letter:
board[4] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[4] == opp_letter and board[5] == opp_letter:
if board[3] != human_letter:
board[3] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a bottom horizontal win
if board[6] == opp_letter and board[7] == opp_letter:
if board[8] != human_letter:
board[8] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[6] == opp_letter and board[8] == opp_letter:
if board[7] != human_letter:
board[7] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[7] == opp_letter and board[8] == opp_letter:
if board[6] != human_letter:
board[6] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a left vertical win
if board[0] == opp_letter and board[3] == opp_letter:
if board[6] != human_letter:
board[6] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[0] == opp_letter and board[6] == opp_letter:
if board[3] != human_letter:
board[3] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[3] == opp_letter and board[6] == opp_letter:
if board[0] != human_letter:
board[0] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a left vertical win
if board[0] == opp_letter and board[3] == opp_letter:
if board[6] != human_letter:
board[6] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[0] == opp_letter and board[6] == opp_letter:
if board[3] != human_letter:
board[3] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[3] == opp_letter and board[6] == opp_letter:
if board[0] != human_letter:
board[0] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a middle vertical win
if board[1] == opp_letter and board[4] == opp_letter:
if board[7] != human_letter:
board[7] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[1] == opp_letter and board[7] == opp_letter:
if board[4] != human_letter:
board[4] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[4] == opp_letter and board[7] == opp_letter:
if board[1] != human_letter:
board[1] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a right vertical win
if board[2] == opp_letter and board[5] == opp_letter:
if board[8] != human_letter:
board[8] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[2] == opp_letter and board[8] == opp_letter:
if board[5] != human_letter:
board[5] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[5] == opp_letter and board[8] == opp_letter:
if board[2] != human_letter:
board[2] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a left to right diagonal win
if board[0] == opp_letter and board[4] == opp_letter:
if board[8] != human_letter:
board[8] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[4] == opp_letter and board[8] == opp_letter:
if board[0] != human_letter:
board[0] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[0] == opp_letter and board[8] == opp_letter:
if board[4] != human_letter:
board[4] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
#check for a right to left diagonal win
if board[2] == opp_letter and board[4] == opp_letter:
if board[6] != human_letter:
board[6] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[4] == opp_letter and board[6] == opp_letter:
if board[2] != human_letter:
board[2] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
if board[2] == opp_letter and board[6] == opp_letter:
if board[4] != human_letter:
board[4] = opp_letter
winner = True
print ("--COMPUTER WINS--")
show_board()
play_again()
def block_human_win():
global open_boxes
#Block top horizontal win
if board[0] == human_letter and board[1] == human_letter:
if board[2] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[2] = opp_letter
show_board()
human_first()
if board[0] == human_letter and board[2] == human_letter:
if board[1] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[1] = opp_letter
show_board()
human_first()
if board[1] == human_letter and board[2] == human_letter:
if board[0] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[0] = opp_letter
show_board()
human_first()
#Block middle horizontal win
if board[3] == human_letter and board[4] == human_letter:
if board[5] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[5] = opp_letter
show_board()
human_first()
if board[3] == human_letter and board[5] == human_letter:
if board[4] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[4] = opp_letter
show_board()
human_first()
if board[4] == human_letter and board[5] == human_letter:
if board[3] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[3] = opp_letter
show_board()
human_first()
#Block bottom horizontal win
if board[6] == human_letter and board[7] == human_letter:
if board[8] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[8] = opp_letter
show_board()
human_first()
if board[6] == human_letter and board[8] == human_letter:
if board[7] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[7] = opp_letter
show_board()
human_first()
if board[7] == human_letter and board[8] == human_letter:
if board[6] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[6] = opp_letter
show_board()
human_first()
#Block left vertical win
if board[0] == human_letter and board[3] == human_letter:
if board[6] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[6] = opp_letter
show_board()
human_first()
if board[0] == human_letter and board[6] == human_letter:
if board[3] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[3] = opp_letter
show_board()
human_first()
if board[3] == human_letter and board[6] == human_letter:
if board[0] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[0] = opp_letter
show_board()
human_first()
#Block middle vertical win
if board[1] == human_letter and board[4] == human_letter:
if board[7] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[7] = opp_letter
show_board()
human_first()
if board[1] == human_letter and board[7] == human_letter:
if board[4] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[4] = opp_letter
show_board()
human_first()
if board[4] == human_letter and board[7] == human_letter:
if board[1] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[1] = opp_letter
show_board()
human_first()
#Block right vertical win
if board[2] == human_letter and board[5] == human_letter:
if board[8] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[8] = opp_letter
show_board()
human_first()
if board[2] == human_letter and board[8] == human_letter:
if board[5] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[5] = opp_letter
show_board()
human_first()
if board[5] == human_letter and board[8] == human_letter:
if board[2] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[2] = opp_letter
show_board()
human_first()
#Block left to right diagonal win
if board[0] == human_letter and board[4] == human_letter:
if board[8] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[8] = opp_letter
show_board()
human_first()
if board[0] == human_letter and board[8] == human_letter:
if board[4] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[4] = opp_letter
show_board()
human_first()
if board[4] == human_letter and board[8] == human_letter:
if board[0] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[0] = opp_letter
show_board()
human_first()
#Block right to left diagonal win
if board[2] == human_letter and board[4] == human_letter:
if board[6] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[6] = opp_letter
show_board()
human_first()
if board[2] == human_letter and board[6] == human_letter:
if board[4] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[4] = opp_letter
show_board()
human_first()
if board[4] == human_letter and board[6] == human_letter:
if board[2] != opp_letter:
can_block = True
open_boxes -= 1
print('Computer is thinking...')
print('Computer blocks your winning move.')
board[2] = opp_letter
show_board()
human_first()
def human_first():
can_block = False
global open_boxes
if open_boxes > 0:
while True:
move = input('Please pick a number from 1 - 9: ')
if move.isdigit():
move = int(move) - 1
else:
print('Sorry, please pick a number from 1 - 9: ')
human_first()
winner = False
if board[move] != 'x' and board[move] != 'o':
board[move] = human_letter
open_boxes -= 1
show_board()
else:
print('\n')
print('Sorry that space is taken. Try again')
print('\n')
show_board()
human_first()
if checkAll(human_letter) == True:
winner = True
print ("--HUMAN WINS--")
print ('\n')
play_again()
break;
computer_move()
if checkAll(opp_letter) == True:
winner = True
print ("--COMPUTER WINS--")
print ('\n')
play_again()
break;
else:
print('--DRAW--')
play_again()
def computer_first():
global open_boxes
if open_boxes > 0:
computer_move()
while True:
move = input('Please pick a number from 1 - 9: ')
if move.isdigit():
move = int(move) - 1
else:
print('Sorry, please pick a number from 1 - 9: ')
human_first()
winner = False
if board[move] != 'x' and board[move] != 'o':
board[move] = human_letter
open_boxes -= 1
show_board()
else:
print('\n')
print('Sorry that space is taken. Try again')
print('\n')
show_board()
human_first()
if checkAll(human_letter) == True:
winner = True
print ("--HUMAN WINS--")
print ('\n')
play_again()
break;
computer_move()
if checkAll(opp_letter) == True:
winner = True
print ("--COMPUTER WINS--")
print ('\n')
play_again()
break;
else:
print('--DRAW--')
play_again()
def who_goes_first():
global board
global open_boxes
open_boxes = 9
print ('Welcome to Tic Tac Toe!This is your game board: ')
print ('\n')
show_board()
choose_letter()
print ('\n')
print('The first player will be chosen at random.')
print('...')
first = random.randint(0,1)
if first == 1:
print('Human goes first')
human_first()
else:
print('Computer goes first')
computer_first()
def play_again():
global board
board = [1,2,3,4,5,6,7,8,9]
print('Do you want to play again? Y/N: ')
answer = input().lower()
if answer in ('y','ye','yes'):
who_goes_first()
elif answer in ('n','no'):
print('Hope you enjoyed the game!')
sys.exit()
else:
print('Sorry, I didn\'t get that..')
play_again()
who_goes_first()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T00:40:08.810",
"Id": "409286",
"Score": "0",
"body": "Two big things come to mind. 1) don't use globals- pass everything as function arguments and return values, it will make it easier to reset things. 2) use `board` for display purposes only. Its difficult to check anything more than move validity using the literal game board matrix. Instead, keep 8 lists (one for each potential 3-in-a-row), and remove elements as moves are made."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T23:11:16.173",
"Id": "211648",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"tic-tac-toe",
"ai"
],
"Title": "Repetitive Tic-Tac-Toe AI game with Python 3"
} | 211648 |
<p><a href="https://en.wikipedia.org/wiki/Docker_(software)" rel="nofollow noreferrer">Docker</a> is an open source project to pack, ship and run any application as a lightweight, portable, self-sufficient container. The same container that a developer builds and tests on a laptop can run at scale, in production, on VMs, bare metal, OpenStack clusters, public clouds and more.</p>
<p>See <a href="https://www.docker.com/" rel="nofollow noreferrer">the official website</a> for details.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T23:52:37.380",
"Id": "211649",
"Score": "0",
"Tags": null,
"Title": null
} | 211649 |
Docker provides a high-level API to containerize processes and applications with some degree of isolation and repeatability across servers. Docker supports both Linux and Windows containers running on x86/64, ARM and other architectures. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T23:52:37.380",
"Id": "211650",
"Score": "0",
"Tags": null,
"Title": null
} | 211650 |
<p>I am a rookie of coding and I have written a c++ procedure which calls the Eigen library to do the linear operation of the matrix. Please help me to improve the efficiency of the loop.</p>
<pre><code>#include <iostream>
#include <fstream>
#include <Eigen/Dense>
#include <time.h>
using namespace std;
int main()
{
// Weight coefficient matrix
Eigen::MatrixXd wi_1,wi_2,wi_3,wi_4;
wi_1.resize(100,2);
wi_2.resize(100,100);
wi_3.resize(100,100);
wi_4.resize(5,100);
wi_1.setOnes();
wi_2.setOnes();
wi_3.setOnes();
wi_4.setOnes();
// Bias vector
Eigen::VectorXd bias_1,bias_2,bias_3,bias_4,Y;
bias_1.resize(100);
bias_2.resize(100);
bias_3.resize(100);
bias_4.resize(5);
bias_1.setOnes();
bias_2.setOnes();
bias_3.setOnes();
bias_4.setOnes();
Eigen::Matrix<double,5,1> y_mean;
Eigen::Matrix<double,5,1> y_scale;
Eigen::Matrix<double,2,1> x_mean;
Eigen::Matrix<double,2,1> x_scale;
y_mean.setOnes();
y_scale.setOnes();
y_mean.setOnes();
x_scale.setOnes();
int n = 0;
int layer;
clock_t start,finish;
double totaltime;
start=clock();
while (n<10000)
{
Y.resize(2);
layer = 0;
Y << 0.185, 0.285;//inputx[1], x[0];
Y = (Y.array() - x_mean.array()) / x_scale.array();
//ANN forward
while (layer < 4)
{
layer++;
switch (layer) {
case 1:{
Y = wi_1 * Y + bias_1;
// Info << "ANN forward layer1" << endl;
break;
}
case 2:{
Y = wi_2 * Y + bias_2;
// Info << "ANN forward layer2" << endl;
break;
}
case 3:{
Y = wi_3 * Y + bias_3;
// Info << "ANN forward layer3" << endl;
break;
}
case 4:{
Y = wi_4 * Y + bias_4;
// Info << "ANN forward layer4" << endl;
break;
}
default:{
cout<<"error"<<endl;
break;
}
}
//Relu activation function
if (layer < 4)
{
for (int i = 0; i < Y.size(); i++)
{
Y(i) = ((Y(i) > 0) ? Y(i) : 0);
}
}
}
//inverse standardization
Y = Y.array() * y_scale.array() + y_mean.array();
n++;
}
finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC*1000;
cout<<"\n Running time is "<<totaltime<<"ms!"<<endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T03:09:27.097",
"Id": "409294",
"Score": "4",
"body": "Welcome to Code Review. Please tell us more about the task that this code performs. (MathJax is available for mathematical notation.) See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T05:57:31.460",
"Id": "409298",
"Score": "2",
"body": "Also, the current title is very generic. Unless your code also is very generic, please change your title to be more specific. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T02:53:28.913",
"Id": "211652",
"Score": "1",
"Tags": [
"c++",
"eigen"
],
"Title": "Calling Eigen library to do the linear operation of the matrix"
} | 211652 |
<p>At the moment I'd like recommendation where I can change and what I can use to improve on simplicity and modularity. If I'm practicing good naming conventions as to provide clean readable code. Any critique is much appreciated. </p>
<pre><code>import time
import re
import requests
from bs4 import BeautifulSoup, SoupStrainer
import pandas as pd
import time
SESSION = requests.Session()
""" This is the Google Analytics Selector Section """
class myGoogleSession:
def fetch_google_xml(self, URL, country_code):
format_url = f"{URL}{country_code}"
response = SESSION.get(format_url)
soup = BeautifulSoup(response.text, 'xml',
parse_only=SoupStrainer('channel'))
return soup
google_session = myGoogleSession()
def google_trends_retriever(URL, country_code):
xml_soup = google_session.fetch_google_xml(URL, country_code)
print(country_code)
return[(title.text, re.sub("[+,]", "", traffic.text))
for title, traffic in zip(xml_soup.find_all('title')[1:],
xml_soup.find_all('ht:approx_traffic'))]
def create_pdTrend(data):
check_panda = pd.DataFrame(
google_trends_retriever(GoogleURL, data),
columns=['Title', 'Score']
)
if len(check_panda) == 0:
print('No available data')
else:
return check_panda
""" This is the Country Code Selector Section """
country_code_list = []
class myCountryCodeSession:
def fetch_countrycode_html(self, URL):
response = SESSION.get(URL)
soup = BeautifulSoup(response.text, 'html.parser',
parse_only=SoupStrainer('table'))
return soup
countryCode_session = myCountryCodeSession()
def parse_row(url):
rows = countryCode_session.fetch_countrycode_html(url)
_rows = rows.findChildren(['td', 'tr'])
for row in _rows:
cells = row.findChildren('td')[2:3]
for cell in cells:
value = cell.string
country_code_list.append(value[:2])
return None
def create_pdCountryCode(country_code):
return pd.DataFrame({'Country_Code': country_code})
def iterate_List(data):
i = 1
while i <= 239:
selected_CountryCode = get_data_fromList(i)
print(create_pdTrend(selected_CountryCode))
i += 1
else:
print('Has reach the end of i ' + str(i))
def get_data_fromList(num):
key = num-1
for i in country_code_list[key:num]:
return str(i)
if __name__ == '__main__':
""" URL Section """
GoogleURL = "https://trends.google.com/trends/trendingsearches/daily/rss?geo="
CountryCodeURL = "https://countrycode.org/"
"""-------------"""
start = time.time()
print("hello")
"""Country Code Section """
parse_row(CountryCodeURL)
"""---------------------"""
"""Google Analytics Section """
iterate_List(country_code_list)
"""-------------------------"""
end = time.time()
print(end - start)
</code></pre>
| [] | [
{
"body": "<h1><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a></h1>\n\n<p>This is the official Python style guide. If you are interested in good naming conventions and other good practices, you can start here.</p>\n\n<p>Among other things, you code would benefit from:</p>\n\n<ul>\n<li>variable name using <code>lower_snake_case</code>;</li>\n<li>class name using <code>PascalCase</code>;</li>\n<li>comments delimited using <code>#</code> and not raw strings in the code;</li>\n<li>redundant/useless parts of the code removed.</li>\n</ul>\n\n<p>A first rewrite would yield:</p>\n\n<pre><code>import re\nimport time\n\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup, SoupStrainer\n\n\nSESSION = requests.Session()\n\n\n# This is the Google Analytics Selector Section\nclass GoogleSession:\n def fetch_google_xml(self, URL, country_code):\n response = SESSION.get(f\"{URL}{country_code}\")\n return BeautifulSoup(\n response.text, 'xml',\n parse_only=SoupStrainer('channel'))\n\n\ngoogle_session = GoogleSession()\n\n\ndef google_trends_retriever(URL, country_code):\n xml_soup = google_session.fetch_google_xml(URL, country_code)\n print(country_code)\n titles = xml_soup.find_all('title')[1:]\n traffics = xml_soup.find_all('ht:approx_traffic')\n return [\n (title.text, re.sub(\"[+,]\", \"\", traffic.text))\n for title, traffic in zip(titles, traffics)\n ]\n\n\ndef create_pd_trend(data):\n check_panda = pd.DataFrame(\n google_trends_retriever(google_URL, data),\n columns=['Title', 'Score'],\n )\n if len(check_panda) == 0:\n print('No available data')\n else:\n return check_panda\n\n\n# This is the Country Code Selector Section\ncountry_code_list = []\n\n\nclass CountryCodeSession:\n def fetch_country_code_html(self, URL):\n response = SESSION.get(URL)\n return BeautifulSoup(\n response.text, 'html.parser',\n parse_only=SoupStrainer('table'))\n\n\ncountry_code_session = CountryCodeSession()\n\n\ndef parse_row(url):\n rows = country_code_session.fetch_country_code_html(url)\n for row in rows.find_all(['td', 'tr']):\n cells = row.find_all('td')[2:3]\n for cell in cells:\n value = cell.string\n country_code_list.append(value[:2])\n\n\ndef iterate_list(data):\n i = 1\n while i <= 239:\n selected_country_code = get_data_from_list(i)\n print(create_pd_trend(selected_country_code))\n i += 1\n else:\n print('Has reach the end of i', i)\n\n\ndef get_data_from_list(num):\n key = num - 1\n for i in country_code_list[key:num]:\n return str(i)\n\n\nif __name__ == '__main__':\n # URL Section\n google_URL = \"https://trends.google.com/trends/trendingsearches/daily/rss?geo=\"\n country_code_URL = \"https://countrycode.org/\"\n # -------------\n start = time.time()\n print(\"hello\")\n\n # Country Code Section\n parse_row(country_code_URL)\n # ---------------------\n\n # Google Analytics Section\n iterate_list(country_code_list)\n # -------------------------\n end = time.time()\n print(end - start)\n</code></pre>\n\n<h1><a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Loop like a native</a></h1>\n\n<p>When I saw</p>\n\n<blockquote>\n<pre><code>def get_data_fromList(num):\n key = num-1\n for i in country_code_list[key:num]:\n return str(i)\n</code></pre>\n</blockquote>\n\n<p>I wondered why you would write such convoluted code. Extracting a sublist of one element to iterate over it and return the first one… You can simplify that to</p>\n\n<pre><code>def get_data_from_list(num):\n return str(country_code_list[num - 1])\n</code></pre>\n\n<p>But I wondered why using a method for that, and saw <em>how</em> you iterated over indices to call this function. Don't. Use a for-loop as it is meant to be used: by iterating over the content directly.</p>\n\n<p>This would yield:</p>\n\n<pre><code>import re\nimport time\n\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup, SoupStrainer\n\n\nSESSION = requests.Session()\n\n\n# This is the Google Analytics Selector Section\nclass GoogleSession:\n def fetch_google_xml(self, URL, country_code):\n response = SESSION.get(f\"{URL}{country_code}\")\n return BeautifulSoup(\n response.text, 'xml',\n parse_only=SoupStrainer('channel'))\n\n\ngoogle_session = GoogleSession()\n\n\ndef google_trends_retriever(URL, country_code):\n xml_soup = google_session.fetch_google_xml(URL, country_code)\n print(country_code)\n titles = xml_soup.find_all('title')[1:]\n traffics = xml_soup.find_all('ht:approx_traffic')\n return [\n (title.text, re.sub(\"[+,]\", \"\", traffic.text))\n for title, traffic in zip(titles, traffics)\n ]\n\n\ndef create_pd_trend(data):\n check_panda = pd.DataFrame(\n google_trends_retriever(google_URL, data),\n columns=['Title', 'Score'],\n )\n if len(check_panda) == 0:\n print('No available data')\n else:\n return check_panda\n\n\n# This is the Country Code Selector Section\nclass CountryCodeSession:\n def fetch_country_code_html(self, URL):\n response = SESSION.get(URL)\n return BeautifulSoup(\n response.text, 'html.parser',\n parse_only=SoupStrainer('table'))\n\n\ncountry_code_session = CountryCodeSession()\n\n\ndef parse_row(url):\n rows = country_code_session.fetch_country_code_html(url)\n return [\n cell.string[:2]\n for row in rows.find_all(['td', 'tr'])\n for cell in row.find_all('td')[2:3]\n ]\n\n\ndef iterate_list(country_codes):\n for country_code in country_codes:\n print(create_pd_trend(str(country_code)))\n else:\n print('Has reach the end of i', len(country_codes))\n\n\nif __name__ == '__main__':\n # URL Section\n google_URL = \"https://trends.google.com/trends/trendingsearches/daily/rss?geo=\"\n country_code_URL = \"https://countrycode.org/\"\n # -------------\n start = time.time()\n print(\"hello\")\n\n # Country Code Section\n country_code_list = parse_row(country_code_URL)\n # ---------------------\n\n # Google Analytics Section\n iterate_list(country_code_list)\n # -------------------------\n end = time.time()\n print(end - start)\n</code></pre>\n\n<h1><a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop writting classes</a></h1>\n\n<p>Your classes add absolutely no value over a single function. You don't store state that you reuse after each call. You don't share state between several functions. They are plain functions in a namespace, just let them be plain functions.</p>\n\n<p>This code can benefit from using a class, but not like that.</p>\n\n<h1><a href=\"https://lxml.de/FAQ.html#why-can-t-lxml-parse-my-xml-from-unicode-strings\" rel=\"nofollow noreferrer\">Parse bytes, not text</a></h1>\n\n<p><code>lxml</code>, which is the underlying parser used when instructing <code>BeautifulSoup</code> to decode <code>'xml'</code> explicitly works with raw bytes rather than decoded text. This is to be able to detect explicit encoding declarations and decode the rest of the document appropriately; so you will never have decoding errors.</p>\n\n<p>This means that you need to feed the <code>response.content</code> rather than <code>response.text</code> to <code>BeautifulSoup</code> when parsing XML.</p>\n\n<h1>Manage your state properly</h1>\n\n<p>Your code heavily relly on global variables and <code>print</code>ing data to work. This is the worst part of your code as it make it barely reusable and harder to test properly (think <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\"><code>unittest</code></a> or <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a>).</p>\n\n<p>Instead of using global variables, pass them around as parameters and return them from your functions.</p>\n\n<p>Instead of printing results, return values from your functions. This make it easier to extract and massage data into your liking.</p>\n\n<p>There is also the global <code>SESSION</code> that is used throughout the code. I'd encapsulate that into a class to have a single session per instance so you can easily crawl several addresses if need be.</p>\n\n<p>My take on the problem would be:</p>\n\n<pre><code>import re\nfrom functools import partial\n\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup, SoupStrainer\n\n\nclass GoogleAnalysis:\n def __init__(self, url):\n session = requests.Session()\n self.get_url = partial(session.get, url)\n\n def _fetch_xml(self, country_code):\n response = self.get_url(params={'geo': country_code})\n return BeautifulSoup(\n response.content, 'xml',\n parse_only=SoupStrainer('channel'))\n\n def _retrieve_trends(self, country_code):\n soup = self._fetch_xml(country_code)\n titles = soup.find_all('title')[1:]\n traffics = soup.find_all('ht:approx_traffic')\n return [\n (title.text, re.sub(\"[+,]\", \"\", traffic.text))\n for title, traffic in zip(titles, traffics)\n ]\n\n def trends(self, country_code):\n df = pd.DataFrame(\n self._retrieve_trends(country_code),\n columns=['Title', 'Score'],\n )\n df['Country Code'] = country_code\n return df\n\n\ndef country_codes(url='https://countrycode.org/'):\n response = requests.get(url)\n soup = BeautifulSoup(\n response.text, 'lxml',\n parse_only=SoupStrainer('table'))\n return [\n cell.string[:2]\n for row in soup.find_all(['td', 'tr'])\n # Some rows don't define row.find_all('td')[2] so filter out\n for cell in row.find_all('td')[2:3]\n ]\n\n\ndef main(url):\n google = GoogleAnalysis(url)\n codes = country_codes()\n return pd.concat([\n google.trends(country_code)\n # Country codes are repeated twice, we only need them once\n for country_code in codes[:len(codes) // 2]\n ])\n\n\nif __name__ == '__main__':\n import time\n start = time.perf_counter()\n print('Hello!')\n trends = main('https://trends.google.com/trends/trendingsearches/daily/rss')\n print(trends.to_string(index=False))\n print(time.perf_counter() - start)\n</code></pre>\n\n<p>Note the <code>print(trends.to_string(index=False))</code> at the end, this could be whatever you like, either printing to CSV or using <code>trends.groupby</code> to redo your old formatting. The idea here is that the computation is done without <code>print</code>ing anything. You get to format the data at the end however you like.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:38:48.263",
"Id": "409355",
"Score": "0",
"body": "I always forget about `BeautifulSoup` being able to parse the `response.content` and not only `response.text`. However, when parsing this SE page it takes about 25ms with the text but about 500ms with the content (using `\"lxml\"` in both cases), so it might actually be slower..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:43:26.423",
"Id": "409358",
"Score": "2",
"body": "@Graipher I never said it would be faster, but safer in that it should avoid decoding errors. And it doesn't surprise me that the bytes approach is slower because `lxml` has to search for an encoding declaration, figure out which it is and decode the remainder of the document using such declaration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:46:06.660",
"Id": "409360",
"Score": "0",
"body": "True, you never said that it would be faster. I just assumed that directly working with the bytes object would be faster somehow..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:48:23.833",
"Id": "409363",
"Score": "0",
"body": "Yes, I did `%timeit BeautifulSoup(r.text, \"lxml\") ` and `%timeit BeautifulSoup(r.content, \"lxml\")` (and then the first one again in case some caching was involved)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:01:26.717",
"Id": "409366",
"Score": "2",
"body": "@Graipher For what it's worth, I added a link to [the FAQ entry of lxml](https://lxml.de/FAQ.html#why-can-t-lxml-parse-my-xml-from-unicode-strings), changed parsing of HTML accordingly and rewrote the paragraph involved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T02:46:41.137",
"Id": "409423",
"Score": "0",
"body": "Thank you for the feedback, time and effort you've given ~ and you're right on how I have wrongly approached the use of classes and not properly utilizing encapsulation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T04:27:39.950",
"Id": "409433",
"Score": "0",
"body": "May I ask one question in terms of being able to create new columns. Etc \n `def trends(self, country_code):\n df = pd.DataFrame(\n self._retrieve_trends(country_code),\n columns=['Title', 'Score'],\n )\n df['Country Code'] = country_code`\nI'd like to add another `df['Date'] = 2019/1/18`\nDo I keep doing `df[ ' .... ' ]` or I'm not sure how to proceed from there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T08:02:05.660",
"Id": "409446",
"Score": "0",
"body": "@Minial https://stackoverflow.com/questions/12555323/adding-new-column-to-existing-dataframe-in-python-pandas"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T10:26:13.643",
"Id": "211674",
"ParentId": "211654",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211674",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T03:25:52.410",
"Id": "211654",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"pandas",
"beautifulsoup"
],
"Title": "Google Analytic Webcrawler for every country code"
} | 211654 |
<p>I've been working through the book Head First C# and this is an exercise from chapter 7, which is about interfaces and abstract classes. </p>
<p>Note that the class design was mandated by the authors, I'm open to suggestions to improve.</p>
<p>I'd like a review on any and all aspects. My code ended up quite a bit different than the book's solution, because it's a few years old and I think "holds back" on newer C#/.NET features and syntax.</p>
<p>In a shared code base, I would include that XML documentation, but since this is just local code for learning, I didn't. Any and all feedback appreciated.</p>
<hr>
<p>The authors' published implementation is <a href="https://github.com/head-first-csharp/third-edition/tree/master/VS2013/Chapter_7/LetsBuildAHouse" rel="noreferrer">here on GitHub</a>. The idea is to implement a floor plan that can be explored, with room connections and doors to the outside. It's done through a WinForms application.</p>
<p>Here is a picture of the plan from the book. Sorry, couldn't find a screenshot. </p>
<p><a href="https://i.stack.imgur.com/SAsL1.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/SAsL1.jpg" alt="floorplan"></a></p>
<p>The app looks like this:</p>
<p><a href="https://i.stack.imgur.com/MtusU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MtusU.png" alt="app"></a></p>
<hr>
<h3>Location.cs</h3>
<pre><code>using System;
namespace House
{
abstract class Location
{
public Location(string name) => Name = name;
public string Name { get; private set; }
public Location[] Exits;
public virtual string Description
{
get
{
string description = $"You're standing in the {Name}. You see exits to the following places: \r\n";
foreach (Location exit in Exits)
{
description += $"— {exit.Name}";
if (exit != Exits[Exits.Length - 1])
{
description += "\r\n";
}
}
return description;
}
}
}
}
</code></pre>
<h3>Room.cs</h3>
<pre><code>using System;
namespace House
{
class Room : Location
{
public Room(string name, string decoration)
: base(name)
{
Decoration = decoration;
}
private string Decoration { get; set; }
public override string Description => $"You see {Decoration}. {base.Description} ";
}
}
</code></pre>
<h3>Outside.cs</h3>
<pre><code>using System;
namespace House
{
class Outside : Location
{
public Outside(string name, bool hot)
: base(name)
{
Hot = hot;
}
private bool Hot { get; }
override public string Description => Hot
? "It's very hot here. " + base.Description
: base.Description;
}
}
</code></pre>
<hr>
<h3>IHasInteriorDoor.cs</h3>
<pre><code>using System;
namespace House
{
interface IHasExteriorDoor
{
string DoorDescription { get; }
Location DoorLocation { get; }
}
}
</code></pre>
<hr>
<h3>OutsideWithDoor.cs</h3>
<pre><code>using System;
namespace House
{
class OutsideWithDoor : Outside, IHasExteriorDoor
{
public OutsideWithDoor(string name, bool hot, string doorDescription)
: base(name, hot)
{
DoorDescription = doorDescription;
}
public string DoorDescription { get; private set; }
public Location DoorLocation { get; set; }
public override string Description => $"{base.Description}\r\n You see {DoorDescription} to go inside.";
}
}
</code></pre>
<h3>RoomWithDoor.cs</h3>
<pre><code>using System;
namespace House
{
class RoomWithDoor : Room, IHasExteriorDoor
{
public RoomWithDoor(string name, string decoration, string doorDescription)
: base(name, decoration)
{
DoorDescription = doorDescription;
}
public string DoorDescription { get; private set; }
public Location DoorLocation { get; set; }
}
}
</code></pre>
<hr>
<p>And here is the WinForms to make it work. Leaving out IDE generated code.</p>
<h3>ExploreTheHouseForm.cs</h3>
<pre><code>using System;
using System.Windows.Forms;
namespace House
{
public partial class ExploreTheHouseForm : Form
{
Location currentLocation;
RoomWithDoor livingRoom;
RoomWithDoor kitchen;
Room diningRoom;
OutsideWithDoor frontYard;
OutsideWithDoor backYard;
Outside garden;
public ExploreTheHouseForm()
{
InitializeComponent();
CreateObjects();
MoveToLocation(livingRoom);
}
private void CreateObjects()
{
// Configure the locations
livingRoom = new RoomWithDoor("living room", "an antique carpet", "an oak door with a brass knob");
kitchen = new RoomWithDoor("kitchen", "stainless steel appliances", "a screen door");
diningRoom = new Room("dining room", "a crystal chandelier");
frontYard = new OutsideWithDoor("front yard", false, livingRoom.DoorDescription);
backYard = new OutsideWithDoor("back yard", true, kitchen.DoorDescription);
garden = new Outside("garden", false);
// Configure the exits
livingRoom.Exits = new Location[] { diningRoom };
kitchen.Exits = new Location[] { diningRoom };
diningRoom.Exits = new Location[] { livingRoom, kitchen };
frontYard.Exits = new Location[] { backYard, garden };
backYard.Exits = new Location[] { frontYard, garden };
garden.Exits = new Location[] { frontYard, backYard };
// Configure exterior doors
livingRoom.DoorLocation = frontYard;
frontYard.DoorLocation = livingRoom;
kitchen.DoorLocation = backYard;
backYard.DoorLocation = kitchen;
}
private void MoveToLocation(Location location)
{
currentLocation = location;
ExitsComboBox.Items.Clear();
foreach (Location exit in location.Exits)
{
ExitsComboBox.Items.Add(exit.Name);
}
ExitsComboBox.SelectedIndex = 0;
DescriptionTextBox.Text = currentLocation.Description;
ShowGoThroughExteriorDoorButton(currentLocation);
}
private void ShowGoThroughExteriorDoorButton(Location location)
{
if (location is IHasExteriorDoor)
{
GoThroughExteriorDoorButton.Visible = true;
return;
}
GoThroughExteriorDoorButton.Visible = false;
}
private void GoHereButton_Click(object sender, EventArgs e)
{
MoveToLocation(currentLocation.Exits[ExitsComboBox.SelectedIndex]);
}
private void GoThroughExteriorDoorButton_Click(object sender, EventArgs e)
{
IHasExteriorDoor locationWithExteriorDoor = currentLocation as IHasExteriorDoor;
MoveToLocation(locationWithExteriorDoor.DoorLocation);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:15:14.453",
"Id": "409349",
"Score": "0",
"body": "The winforms screen gives the option to go through the exterior door, but whatever is behind the exterior door doesn't get listed in the available places? What happens if the kitchen had multiple exterior doors to multiple places? What if the entire house was just a kitchen?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T22:21:15.787",
"Id": "409412",
"Score": "4",
"body": "If you are interested in the general problem of how to write text-based adventures, I encourage you to look into `Inform7`, an exceedingly clever language for writing such adventures. If you're interested in learning about virtual machines for implementing such adventures, I did a series on my blog a few years ago about the Z-machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T13:36:18.193",
"Id": "409488",
"Score": "3",
"body": "As a bonus, on a Z-machine code for this problem will occupy less than a kilobyte. You won't be able to compile the above code into a .NET assembly that takes up that much. (This is another way of saying \"in Ye Olde Days we didn't have no interfaces and abstract classes\". However, we were also much more likely to be eaten by a grue, so it all evens out in the end.)"
}
] | [
{
"body": "<p>I have a general rule: if I see string concatenation with a loop I assume it's not the best way of doing it. Let's look at this:</p>\n\n<pre><code>foreach (Location exit in Exits)\n{\n description += $\"— {exit.Name}\";\n if (exit != Exits[Exits.Length - 1])\n {\n description += \"\\r\\n\";\n }\n}\n</code></pre>\n\n<p>I see this pattern a lot. What you need is <code>Select</code> with <code>string.Join</code>:</p>\n\n<pre><code>var exitList = string.Join(Environment.NewLine, Exits.Select(exit => $\"— {exit.Name}\"));\n</code></pre>\n\n<p>I've used <code>Environment.NewLine</code> because I like using well-named constants. Random aside: <code>\\r</code> is a Carriage Return and <code>\\n</code> is a Line Feed. The terminology comes from physical printers. Another reason I prefer <code>Environment.NewLine</code> is that it means you don't have to know and remember that.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>A comment notes that <code>Environment.NewLine</code> is different on Windows vs Linux/Unix. I think that's important to know and I really should have mentioned it the first time. As the comment exchange shows, it's really easy to get platforms and line-endings mixed up which I think illustrates the usefulness of the constant.</p>\n\n<hr>\n\n<p>The <code>Name</code> property of <code>Location</code> is only set in the constructor. You can use a read-only auto property instead of a private set one:</p>\n\n<pre><code>public string Name { get; }\n</code></pre>\n\n<hr>\n\n<p><code>Outside.Description</code> could be using string interpolation like the other Description properties.</p>\n\n<hr>\n\n<p>You're missing your access modifiers on your class declarations. MS guidelines state that they should always be specified.</p>\n\n<hr>\n\n<p>I'm not aware of a convention for it but <code>override public string</code> seems to be an odd order to me. I would expect the access modifier first: <code>public override string</code>. The main thing is to keep that consistent though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:26:43.977",
"Id": "409350",
"Score": "2",
"body": "`Environment.NewLine` is better for working with Windows or Linux because it contains a different value depending on the OS. For Windows, `Environment.NewLine` is \"\\r\\n\" and on Linux, it is \"\\r\", but by using `Environment.NewLine` you do not need to worry about those details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:34:19.813",
"Id": "409353",
"Score": "1",
"body": "@RickDavin - yes, that's true. I think that `\\r` was old mac though, no? Unix/linux use `\\n` AFAIK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:59:18.997",
"Id": "409377",
"Score": "0",
"body": "My mistake. Yes Linux is \"\\n\". See https://stackoverflow.com/questions/1015766/difference-between-n-and-environment-newline"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T10:06:57.927",
"Id": "211671",
"ParentId": "211662",
"Score": "23"
}
},
{
"body": "<p>In this code block here:</p>\n\n<pre><code>...\nOutsideWithDoor backYard;\nOutside garden;\n\npublic ExploreTheHouseForm()\n{\n InitializeComponent();\n CreateObjects(); // <--- bleh\n MoveToLocation(livingRoom);\n}\n</code></pre>\n\n<p>This is call to the <code>CreateObject()</code> method, is something I don't like to see in code (it could be a personal style issue) but if you are constructing an object, then all code related to the construction of an object should just stay in the constructor...</p>\n\n<p>I would prefer that it ended up looking like</p>\n\n<pre><code>...\nprivate readonly OutsideWithDoor _backYard; // now it can be readonly\nprivate readonly Outside _garden;\n\npublic ExploreTheHouseForm()\n{\n InitializeComponent();\n\n ...\n _backYard = new OutsideWithDoor(\"back yard\", true, kitchen.DoorDescription);\n _garden = new Outside(\"garden\", false);\n\n MoveToLocation(livingRoom);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T13:20:51.527",
"Id": "409581",
"Score": "1",
"body": "\"all code related to the construction of an object should just stay in the constructor\" I have the disagree with that. If it's a one-liner? Do it inline - no point creating helper methods. But for more complex initializations separating logically independent parts into their own methods keeps methods small, simple and self-documenting. Otherwise we end up with a giant constructor method that requires comments to separate the different parts. Now you certainly do want to keep things readonly, but the usual solution is to simply return the created object and assign it in the constructor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:32:41.780",
"Id": "211704",
"ParentId": "211662",
"Score": "6"
}
},
{
"body": "<p>You've already made a decent effort to <strong>make your types immutable</strong> by setting its properties in a constructor and providing get-only access, not set - like you have with <code>Location.Name</code> for example. This is good practice whenever it is reasonable to do so (because, among other things, this means you can pass objects around without ever worrying that something else will change their state unexpectedly). However, I note that <code>Location.Exits</code> is a public field, which means it could be replaced with another array while the program is running - but the house is supposed to be fixed in structure. It would be better as a get-only public property, passed as another parameter in the constructor.</p>\n\n<p>More subtly, not only could someone do something like <code>currentLocation.Exits = ...</code>, which the above advice would prevent; someone could also do <code>currentLocation.Exits[0] = ...</code>, and again they are changing something that is supposed to be fixed. (When I say \"someone\", understand that that could mean \"you, by mistake\", especially in a larger more complex program). Since you mentioned you have been learning about <strong>interfaces</strong>, the public get accessor for <code>Location.Exits</code> should be an <code>IEnumerable<Location></code>, which lets things enumerate through the exits array to see what they are, but not change them. (<em>If you've not used generics yet, don't worry too much about this for now</em>).</p>\n\n<p>So it would end up like this:</p>\n\n<pre><code>abstract class Location\n{\n public Location(string name, Location[] exits)\n {\n Name = name;\n _exits = exits;\n }\n\n public string Name { get; }\n\n private Location[] _exits;\n public IEnumerable<Location> Exits => _exits;\n\n // ...\n}\n</code></pre>\n\n<p>(<em>Secretly, I'm not super-happy about passing in exits as an array, either. Again, someone could change that array after creating the <code>Location</code>. I'd rather pass in exits as an <code>IEnumerable<Location></code> and copy them into a new array or other container type private to the <code>Location</code>. But that raises some design and object ownership questions that aren't too relevant here so let's not worry about that</em>).</p>\n\n<hr>\n\n<p>Digging deeper on locations/exits - a couple of things here, which are probably too large a change to worry about for this exercise, but something to think about in future.</p>\n\n<p>Firstly, <code>OutsideWithDoor</code> inherits from <code>Outside</code> and implements the <code>IHasExteriorDoor</code> interface. This works for your purposes, but means the question of whether or not an exit from one location to the next has a door depends on the type of the locations, whereas logically speaking it's a property of the connection between them. (It's also limited to only one door per location, and a few other tricky bits - <strong>prefer to avoid unnecessary inheritance</strong>, and <strong>prefer composition over inheritance</strong>). So, I would suggest a <code>LocationConnection</code> type, where <code>Location</code>s are joined by <code>LocationConnection</code>s rather than directly to other <code>Location</code>s, and a <code>LocationConnection</code> can either have a door or not (a boolean property).</p>\n\n<p>Secondly, <code>Location</code> exits are bi-directional, that is, if you can go from one location to another, you can always go back, too. That makes sense (if you go from the kitchen to the dining room, it'd be very odd to be unable to go back to the kitchen!) but depends on your initialization code always getting that right, which is a common source of bugs. (What if the building was a mansion, with a hundred rooms!?) This problem could go away if that <code>LocationConnection</code> type were well-implemented, someone could travel along it in either direction and it only needs to be coded once. Something to bear in mind in future: <strong>whenever you have to remember to write BA if you write AB, someone's going to forget to do it</strong>. Make their (your) lives easier!</p>\n\n<p>Introducing that new type may be a bigger change than is really justified for this code review, but it could solve a couple of potential problems.</p>\n\n<hr>\n\n<p>A couple of very minor comments on <code>ShowGoThroughExteriorDoorButton</code>. Firstly, the name of the method is OK, but it sounds like it's <em>always</em> going to show that button. I'd call it <code>ShowOrHide...</code>, though that's just my personal preference. Also, the if-statement in that method is a bit inelegant. I'd write simply:</p>\n\n<pre><code>GoThroughExteriorDoorButton.Visible = (location is IHasExteriorDoor);\n</code></pre>\n\n<p>...which gets rid of those naked <code>true</code> and <code>false</code> values, and also gets rid of that ugly <code>return</code> halfway through the method. In general, <strong>prefer methods to have a single point of exit, at the end</strong>, though this isn't always practical, especially when you start to use exceptions.</p>\n\n<hr>\n\n<p>Always specify <strong>access modifiers</strong>, especially <code>private</code> for all those fields on the <code>ExploreTheHouseForm</code>. Also, a common convention for <strong>private fields</strong> is to prefix them with an underscore, e.g. <code>private Location _currentLocation;</code>, though this is not universally followed - I like it because it helps make obvious what's a parameter or local variable, and what's a member variable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T21:45:04.293",
"Id": "409411",
"Score": "2",
"body": "The desire to have the `Location` immutable and take the exits in the constructor is great, but it seems incompatible with two-way travel. The kitchen has an exit to the dining room, and the dining room has an exit to to the kitchen. In order to follow your implementation advice, both would have to be created before the other. The proposed `LocationConnection` class seems to have the same chicken and egg problem preventing immutability. It will have to reference the locations it connects, and they will have to reference it. How would you resolve this conflict?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T22:34:18.683",
"Id": "409413",
"Score": "2",
"body": "Fair point. One possible solution would be to create the Locations without exit information, then create a list/LUT of LocationConnections. The Location then wouldn't itself hold references to its exits - every time it wanted to know, it would have to check the LocationConnection list. Is that better or worse than just allowing the Location class to be mutable? It becomes a judgement call at that point and depends on how the classes will be used. Mutable is great \"whenever it is reasonable to do so\"... it isn't always."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T02:36:29.907",
"Id": "409422",
"Score": "1",
"body": "Very interesting answer, thank you! I'll be taking this into consideration in the future!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T08:21:52.197",
"Id": "409449",
"Score": "0",
"body": "Comintern's (good) answer provides some examples of what the exit/connection types might look like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T13:08:18.217",
"Id": "409579",
"Score": "1",
"body": "@MrMindor The usual way around this (apart from redesigning to avoid circular references) is to use a builder pattern during creation which is mutable and generate immutable classes from that one."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T18:59:36.717",
"Id": "211716",
"ParentId": "211662",
"Score": "10"
}
},
{
"body": "<p>The other reviews covered many of the main points I'd raise, but there are a handful of others.</p>\n\n<hr>\n\n<p>Constructors in abstract classes should be <code>protected</code>, not <code>public</code>:</p>\n\n<blockquote>\n<pre><code>public Location(string name) => Name = name; \n</code></pre>\n</blockquote>\n\n<p>You can't create a new instance of the abstract class, so it is for all intents and purposes <code>protected</code> anyway. Make the access modifier match the behavior.</p>\n\n<hr>\n\n<p>I'm not sure that I like some of the naming. For example, <code>CreateObjects()</code> gives only the slightest clue as to what it is doing. I'd probably go with something more along the lines of <code>GenerateMap()</code>. A couple of the member names are also a little ambiguous as to how they function - for example, which room is <code>IHasExteriorDoor.DoorLocation</code> relative to?</p>\n\n<hr>\n\n<p>Speaking of doors (keeping in mind that I'm not sure how much was proscribed by the exercise), I also think I find it a bit more natural to have the exits be the primary motive object. It's more natural to me to think of \"using a door\" than it is to think of \"leaving a room\". To me, a room is a static thing - it <strong><em>has</em></strong> exits, but you don't really use a room by leaving it. I'd consider building your map from the standpoint of the connections between the locations instead of the locations themselves. Something more like this:</p>\n\n<pre><code>public interface ILocation\n{\n string Name { get; }\n string Description { get; }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public interface IExit\n{\n // TODO: my naming sucks too.\n ILocation LocationOne { get; }\n ILocation LocationTwo { get; }\n // Takes the room you're exiting as a parameter, returns where you end up.\n ILocation Traverse(ILocation from);\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public abstract class Location : ILocation\n{\n private readonly IReadOnlyList<IExit> _exits;\n\n protected Location(string name, string description, IEnumerable<IExit> exits)\n {\n _exits = exits.ToList();\n }\n\n public IEnumerable<IExit> Exits => _exits;\n\n // ...other properties...\n}\n</code></pre>\n\n<p>That lets you concentrate on the spatial relationships between the locations from a more natural direction (IMO and no pun intended). You'll likely find this to be more easily extensible down the road when you need to, say close or lock a door:</p>\n\n<pre><code>public interface Door : IExit\n{\n bool IsOpen { get; }\n bool IsLocked { get; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T20:18:53.407",
"Id": "412423",
"Score": "0",
"body": "Why do you have both a `ILocation` interface and a `Location` abstract class? Since you have the `Location` abstract class I'd prefer to move `Name` and `Description` to `Location` as abstract properties."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T20:34:00.903",
"Id": "412424",
"Score": "1",
"body": "@inwenis That would fall under the `// ...other properties...` comment. The example `Location` was intended to highlight the `Exits`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T21:38:39.153",
"Id": "412429",
"Score": "0",
"body": "I've read other reviwes and seems the `ILocation` can be used to pass locations as immutable objects. It's nice but without any comments I would recommennd mering them. OK, maybe now after I have seen what it can be used for I would have my doubts."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T23:55:59.233",
"Id": "211727",
"ParentId": "211662",
"Score": "7"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/211671/16504\">RobH's review</a> covers syntax and style well so I won't go into that. Instead I'd like to give my take on feedback given by <a href=\"https://codereview.stackexchange.com/a/211704/16504\">Svek</a> and <a href=\"https://codereview.stackexchange.com/a/211716/16504\">BittermanAndy</a>. </p>\n\n<h2>Separation Of Concerns</h2>\n\n<p>I think Svek's commentary about the <code>CreateObjects</code> method is spot on, but I don't think it goes far enough. The need for such a method in the first place hints that the <code>ExploreTheHouseForm</code> class is doing to much. With the current implementation, each of the rooms is a field on the form. This effectively makes the <code>ExploreTheHouseForm</code> the house itself. As such it would be more aptly named <code>ExplorableHouseForm</code>.</p>\n\n<p>In general (and this becomes ever more important as you get into more complex projects) we want to separate the presentation of the data from the data itself.</p>\n\n<p>The form <em>is the UI</em> it already has the duty to present the data to the user. It shouldn't also <em>be the data</em>. I would much rather the house be constructed elsewhere and passed to the form's constructor:</p>\n\n<pre><code> public ExploreTheHouseForm(Location initialRoom)\n {\n InitializeComponent();\n MoveToLocation(initialRoom);\n }\n</code></pre>\n\n<p>With this simple change, you can remove all the individual <code>Location</code> fields from <code>ExploreTheHouseForm</code> with the exception of <code>currentLocation</code>. Also, if you desire, you can use the same form to explore any number of different houses without further modification.</p>\n\n<h2>Immutability</h2>\n\n<p>A fair amount of BittermanAndy's advice (as of the time of this writing, his post was updated at least once since I started) was to try to make your <code>Location</code> class immutable. Since with the overall design as it is, locations need to reference each other, you run into a chicken & egg scenario preventing immutability where each <code>Location</code> needs their neighbors to be created before them. I don't see a way around this, however if you have your locations implement an interface, and write your form to consume the interface rather than <code>Location</code> you can get much of the same benefit of actual immutability.</p>\n\n<pre><code>public interface ILocation\n{\n public string Name { get; }\n public IList<ILocation> Exits {get;}\n public string Description { get;}\n}\n</code></pre>\n\n<p>In <code>ILocation</code> we only specify the <code>get</code> portions of the properties. This means to consumers of <code>ILocation</code> the properties are effectively read-only even if the implementing classes implement the <code>set</code>. We also declare <code>Exits</code> as a collection of <code>ILocation</code> rather than <code>Location</code> so that accessed members are also read-only to consumers. </p>\n\n<p>You don't have to change much about <code>Location</code> itself:</p>\n\n<pre><code>public abstract class Location: ILocation\n{\n ...\n //private field to back Exits property. \n private IList<ILocation> _exits;\n\n public IList<ILocation> Exits {\n get\n {\n // AsReadOnly so that consumers are not allowed to modify contents.\n // there are other ways of accomplishing this that may be better overall, but ExploreTheHouseForm accesses Exits by index so we can only change it so much. \n return _exits?.AsReadOnly();\n }\n set{ _exits = value;}\n }\n}\n</code></pre>\n\n<p>Updating <code>ExploreTheHouseForm</code> is also straight forward, simply change the type of the field <code>currentLocation</code> the <code>Location</code> parameters of <code>ExploreTheHouseForm</code>, <code>MoveToLocation</code>, and <code>ShowGoThroughExteriorDoorButton</code> to <code>ILocation</code>:</p>\n\n<pre><code> ...\n private ILocation _currentLocation;\n ...\n public ExploreTheHouseForm(ILocation initialRoom)\n {\n InitializeComponent();\n MoveToLocation(initialRoom);\n }\n ...\n private void MoveToLocation(ILocation location)\n ... \n private void ShowGoThroughExteriorDoorButton(ILocation location)\n</code></pre>\n\n<p>The overall impact of this is that the locations are mutable during construction (by some factory) but once construction is complete, all you work with the read-only <code>ILocation</code></p>\n\n<pre><code>// GenerateHouse returns the entry point of the house.\n\npublic ILocation GenerateHouse()\n{\n // Configure the locations\n var livingRoom = new RoomWithDoor(\"living room\", \"an antique carpet\", \"an oak door with a brass knob\");\n var kitchen = new RoomWithDoor(\"kitchen\", \"stainless steel appliances\", \"a screen door\");\n var diningRoom = new Room(\"dining room\", \"a crystal chandelier\");\n var frontYard = new OutsideWithDoor(\"front yard\", false, livingRoom.DoorDescription);\n var backYard = new OutsideWithDoor(\"back yard\", true, kitchen.DoorDescription);\n var garden = new Outside(\"garden\", false);\n\n // Configure the exits\n livingRoom.Exits = new List<ILocation>() { diningRoom };\n kitchen.Exits = new List<ILocation>() { diningRoom };\n diningRoom.Exits = new List<ILocation> { livingRoom, kitchen };\n frontYard.Exits = new List<ILocation> { backYard, garden };\n backYard.Exits = new List<ILocation> { frontYard, garden };\n garden.Exits = new List<ILocation> { frontYard, backYard };\n\n // Configure exterior doors\n livingRoom.DoorLocation = frontYard;\n frontYard.DoorLocation = livingRoom;\n kitchen.DoorLocation = backYard;\n backYard.DoorLocation = kitchen;\n // return entry point.\n return livingRoom;\n\n}\n</code></pre>\n\n<h2>Location Connectivity</h2>\n\n<p>I agree with the other reviews and comments that pulling the concept of the location connection into a separate class/set of classes would allow for a better design. Locations can have any number of exits, and it is a property of the exit, not the location if that exit is an open archway, a door, or just an abstract dividing line (outdoor location to outdoor location) Comintern does a good job of covering this in <a href=\"https://codereview.stackexchange.com/a/211727/16504\">their review</a> so I won't go into it further. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T08:26:41.133",
"Id": "409450",
"Score": "2",
"body": "Excellent answer. Separating the creation of the house, and presenting the form only with the interface it needs for navigation, solves the creation / immutability problem very nicely. (My edits were fairly minor, by the way)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T13:25:16.673",
"Id": "409582",
"Score": "0",
"body": "\"there are other ways of accomplishing this that may be better overall, but ExploreTheHouseForm accesses Exits by index so we can only change it so much.\". At the very least I don't see any reason to not simply change the return value to `IReadOnlyList` which makes the intent much clearer. Admittedly the better fix for the consumer would be to use IImmutableList from the immutable collections package which really guarantees that the content of the list won't change."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T00:30:24.307",
"Id": "211730",
"ParentId": "211662",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "211730",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T06:34:12.607",
"Id": "211662",
"Score": "20",
"Tags": [
"c#",
"winforms",
"interface",
"xaml"
],
"Title": "House plan design (Head First C#)"
} | 211662 |
<p><strong>Note:</strong> I wasn't trying to follow the POSIX <code>getdelim</code> signature exactly. I needed to add the <code>consume</code> argument for a project I'm working on.</p>
<p>I am pretty new to writing C. It would be great to get some feedback on whether best practices are being followed.</p>
<p>Some things I learned about while writing this code (which might be areas that need improvement)</p>
<ul>
<li>Pointer arithmetic</li>
<li><code>FILE *</code> error handling</li>
</ul>
<pre><code>#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
ssize_t read_until_deliminator(char **buffer, size_t *size, char deliminator,
FILE *file, bool consume)
{
char ch;
char *buffer_pos;
if (buffer == NULL || size == NULL || ferror(file)) {
errno = EINVAL;
return -1;
}
if (buffer == NULL || *size == 0) {
// Empty buffer supplied
*size = 128;
*buffer = malloc(*size);
if (*buffer == NULL) {
errno = ENOMEM;
return -1;
}
}
buffer_pos = *buffer;
for (;;) {
ch = getc(file);
if (ch == EOF) {
break;
}
if ((buffer_pos + 1) == (*buffer + *size)) {
// No more room in buffer
size_t new_size = *size * 2;
char* realloc_buffer = realloc(*buffer, new_size);
if (realloc_buffer == NULL) {
errno = ENOMEM;
return -1;
}
buffer_pos = realloc_buffer + (buffer_pos - *buffer);
*buffer = realloc_buffer;
*size = new_size;
}
*buffer_pos++ = ch;
if (ch == deliminator) {
if (!consume) {
// If not consuming delim roll back buffer
buffer_pos--;
}
break;
}
}
if (ch == EOF && buffer_pos == *buffer) {
return -1;
}
*buffer_pos = '\0';
return buffer_pos - *buffer;
}
int main(void)
{
size_t buffer_size = 50;
char *buffer = malloc(buffer_size);
ssize_t result = read_until_deliminator(&buffer, &buffer_size, 'c', stdin, false);
printf("Result: %zd\n", result);
printf("Buffer Size: %zu\n", buffer_size);
printf("Buffer: %s\n", buffer);
free(buffer);
}
</code></pre>
<p><strong>Minimal working example:</strong> <a href="https://repl.it/repls/SlimEarlyField" rel="nofollow noreferrer">https://repl.it/repls/SlimEarlyField</a></p>
| [] | [
{
"body": "<p>Good job!</p>\n\n<p>A few notes:</p>\n\n<ol>\n<li>It is better to check for a <strong>malloc</strong> error right away instead of going to another function to check. Just like what you did with <strong>realloc</strong>.</li>\n<li>Your function <strong>read_until_deliminator</strong>\nreturns an error but your implementation never checks for this error return\nvalue.</li>\n<li>I will do separation of concern, where you will obtain the input and find the delimiter in different functions. This is just to aid in code maintenance so it helps with readability for you and others.</li>\n</ol>\n\n<p>I will post my changes later in the day.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:38:54.827",
"Id": "211693",
"ParentId": "211663",
"Score": "4"
}
},
{
"body": "<p>If we pass a null buffer, expecting it to be allocated for us, then we'll be surprised, because the first check will return a failure here:</p>\n\n<blockquote>\n<pre><code> if (buffer == NULL || size == NULL || ferror(file)) {\n errno = EINVAL;\n return -1;\n }\n\n if (buffer == NULL || *size == 0) {\n</code></pre>\n</blockquote>\n\n<p>Perhaps those conditional blocks need to be in the opposite order? And the buffer/size check to be <code>&&</code> rather than <code>||</code>?</p>\n\n<p>Kudos for using <code>realloc()</code> correctly (testing the result before assigning to <code>*buffer</code> - you've avoided a common mistake there.</p>\n\n<p>Minor (spelling) - \"delimiter\", not \"deliminator\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:48:29.463",
"Id": "211695",
"ParentId": "211663",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T07:15:29.480",
"Id": "211663",
"Score": "3",
"Tags": [
"beginner",
"c",
"file",
"io"
],
"Title": "Implementation of getdelim"
} | 211663 |
<p>I am a relatively novice programmer, and I am taking steps into graphics programming. I am writing a quick pong clone and want to cap the FPS to save system resources. This is how I have implemented this (I've omitted other code for brevity)</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include "SDL.h"
#include "Windows.h"
#define WIN32_LEAN_AND_MEAN
#define FPS 30
Uint32 starttime, endtime, deltatime;
int main()
{
//initialize SDL and do other stuff
//start game loop
timeBeginPeriod(1);
while (appisrunning)
{
starttime = GetTickCount();
SDL_PollEvent(&event);
if (event.type == SDL_QUIT)
{
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
appisrunning = false;
break;
}
// render stuff here
endtime = GetTickCount();
if (endtime > starttime)
{
deltatime = endtime - starttime;
}
else // handles wraparound
{
deltatime = ((2 ^ 32) - starttime) + endtime;
}
if (deltatime > (1000 / FPS)) {}
else
{
Sleep((1000 / FPS) - deltatime);
}
}
timeEndPeriod(1);
return 0;
}
</code></pre>
<p>I use timeBeginPeriod(1) in an effort to give Sleep() a ~1ms resolution. According to the MSDN documentation, this function sets the timer resolution system wide and can result in higher CPU usage as the scheduler has to switch tasks more often (if I understand correctly). </p>
<p>Is this the right approach for this task? What feedback do you have for me?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T08:52:20.367",
"Id": "409314",
"Score": "1",
"body": "Doesn't SDL have abstractions to keep your code portable (i.e. remove `#include \"Windows.h\"`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:09:09.933",
"Id": "409348",
"Score": "0",
"body": "`GetTickCount()` is **not** affected by `timeBeginPeriod()`. Moreover to count FPS (~33 ms) the default system timer resolution is more than adequate."
}
] | [
{
"body": "<p><strong>Code does not handle \"wrap-around\" correctly.</strong></p>\n\n<p><code>2 ^ 32</code> is the exclusive-or of 32 and 2. That has the value of 34. Instead, as unsigned math is defined to wrap-around, just subtract.</p>\n\n<pre><code>//if (endtime > starttime) {\n// deltatime = endtime - starttime;\n//} else {\n// deltatime = ((2 ^ 32) - starttime) + endtime;\n//}\n\ndeltatime = endtime - starttime;\n</code></pre>\n\n<p><strong>Missing objects</strong></p>\n\n<p><code>event, appisrunning, renderer, window</code> are not obviously declared before use in <code>SDL_PollEvent(&event);</code>. Perhaps an SDL thing?</p>\n\n<p><strong>Unnecessary use of global variables</strong></p>\n\n<p><code>Uint32 starttime, endtime, deltatime;</code> belongs in <code>main()</code>. Or even better, within the loop.</p>\n\n<p><strong>Use an auto formatter</strong></p>\n\n<p>The below code hints at manual formatting. Use an auto formatter and save time.</p>\n\n<pre><code> // render stuff here\n endtime = GetTickCount();\n if (endtime > starttime)\n</code></pre>\n\n<p>An auto formatter would have the below and constant indent amount per level (rather than 2 and sometimes 4 spaces).</p>\n\n<p>Example re-format</p>\n\n<pre><code>#include <stdio.h>\n#include <stdbool.h>\n#include \"SDL.h\"\n#include \"Windows.h\"\n\n#define WIN32_LEAN_AND_MEAN\n#define FPS 30\n\nint main(void) {\n timeBeginPeriod(1);\n while (appisrunning) {\n Uint32 starttime = GetTickCount();\n SDL_PollEvent(&event);\n\n if (event.type == SDL_QUIT) {\n SDL_DestroyRenderer(renderer);\n SDL_DestroyWindow(window);\n SDL_Quit();\n appisrunning = false;\n break;\n }\n\n Uint32 endtime = GetTickCount();\n Uint32 deltatime = endtime - starttime;\n\n if (deltatime > (1000 / FPS)) {\n } else {\n Sleep((1000 / FPS) - deltatime);\n }\n }\n timeEndPeriod(1);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T03:22:42.400",
"Id": "409427",
"Score": "0",
"body": "Thanks for pointing out the unsigned math. The \"missing objects\" were declared earlier in my code. I just left that out for brevity. I agree that the auto formatted code does look cleaner. I think part of the inconsistent indentation was introduced when I was transferring the code to this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T04:01:44.517",
"Id": "409431",
"Score": "0",
"body": "@JasonMills \"I just left that out for brevity.\" --> See [Check that your code works](https://codereview.meta.stackexchange.com/q/1954/29485)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T04:59:34.847",
"Id": "409434",
"Score": "0",
"body": "I'll keep that in mind for the future."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T00:59:56.433",
"Id": "211732",
"ParentId": "211667",
"Score": "2"
}
},
{
"body": "<p>As noted by Toby Speight in the comments, there is no need to use <code>Windows.h</code>. SDL provides <a href=\"https://wiki.libsdl.org/SDL_GetTicks\" rel=\"nofollow noreferrer\"><code>SDL_GetTicks()</code></a> for timing, and <a href=\"https://wiki.libsdl.org/SDL_Delay\" rel=\"nofollow noreferrer\"><code>SDL_Delay()</code></a> for waiting on the current thread.</p>\n\n<hr>\n\n<p>The SDL cleanup code should be outside the main loop. There will probably be other reasons to exit (e.g. pressing the escape key or clicking on a quit button), and we don't want to duplicate that code.</p>\n\n<hr>\n\n<p>Limiting the frame rate:</p>\n\n<ul>\n<li><p>For limiting the rate of physics in a game, standard practice is to use an accumulator and a fixed update time-step, as in the <a href=\"https://gafferongames.com/post/fix_your_timestep/\" rel=\"nofollow noreferrer\">penultimate code listing in this article</a>.</p></li>\n<li><p>For limiting the rate of rendering, we can make sure <a href=\"https://wiki.libsdl.org/SDL_GL_SetSwapInterval\" rel=\"nofollow noreferrer\">vsync is turned on</a>.</p></li>\n<li><p>For limiting the overall frame-rate to prevent excessive CPU consumption (and the rate at which we poll events) there is no clear consensus. For my own opinion, see below.</p></li>\n<li><p>Note that <code>timeBeginPeriod()</code> has some serious disadvantages, <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/timeapi/nf-timeapi-timebeginperiod\" rel=\"nofollow noreferrer\">as mentioned in the MSDN docs</a>:</p>\n\n<blockquote>\n <p>Setting a higher resolution can improve the accuracy of time-out\n intervals in wait functions. However, it can also reduce overall\n system performance, because the thread scheduler switches tasks more\n often. High resolutions can also prevent the CPU power management\n system from entering power-saving modes.</p>\n</blockquote>\n\n<p>Creating issues like these for the entire system is arguably worse than consuming a little extra CPU.</p></li>\n</ul>\n\n<hr>\n\n<p><em>opinion:</em></p>\n\n<p>For a PC game, don't limit the frame rate while the user's attention is on the game. Generally we expect games to run smoothly and respond immediately to user input, and since they occupy the user's full attention, consumption of resources isn't an issue.</p>\n\n<p>If the user minimizes or unfocuses the game window, they want to use resources for something else, so we should use <code>Sleep</code> or <code>SDL_Delay</code> to consume less CPU. It doesn't matter if we wake up slightly late and have a choppy frame rate, because the user isn't paying attention, so there's no reason to call <code>timeBeginPeriod</code>. (The physics will still behave properly if we've <a href=\"https://gafferongames.com/post/fix_your_timestep/\" rel=\"nofollow noreferrer\">fixed the time step</a>, and we may even have paused the game so there's not much to update anyway).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T12:01:30.377",
"Id": "211762",
"ParentId": "211667",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "211732",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T08:34:17.650",
"Id": "211667",
"Score": "6",
"Tags": [
"c",
"timer",
"windows",
"sdl"
],
"Title": "Frame limiting in an SDL game"
} | 211667 |
DXL (DOORS Extension Language) is a scripting language for IBM Rational DOORS. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T08:43:32.913",
"Id": "211669",
"Score": "0",
"Tags": null,
"Title": null
} | 211669 |
<p>I try to implement a thread safe queue with the interrupt function (interrupt all threads who are blocking to take data from queue).</p>
<pre><code>#include <queue>
#include <mutex>
#include <chrono>
#include <thread>
#include <cstdint>
#include <iostream>
#include <condition_variable>
/**
* throw the exception when waiting is interrupted by other threads.
*/
class BlockInterrupt
{
public:
BlockInterrupt()
{
}
};
/**
* RAII, execute the function in destructor.
*/
class Final
{
public:
explicit Final(const std::function<void()>& final)
:m_final(final)
{
}
~Final()
{
try
{
m_final();
}
catch(...)
{
}
}
private:
const std::function<void()> m_final;
};
template<typename T>
class BlockQueue
{
public:
BlockQueue()
{
}
/**
* queue will be destroyed, interrupt all blocking thread.
* the mutex will be locked until the deconstruction is finished.
*/
~BlockQueue()
{
std::unique_lock<std::mutex> lock(m_mutex);
if(m_waiter_count == 0)
{
return;
}
m_interrupted = true;
//wake up all block threads.
m_wait_finished.notify_all();
//wait for all threads are interrupted.
m_interrupt_finished.wait(lock, [this](){return m_waiter_count == 0;});
}
BlockQueue(const BlockQueue&) = delete;
BlockQueue(BlockQueue&&) = delete;
BlockQueue& operator=(const BlockQueue&) = delete;
BlockQueue& operator=(BlockQueue&&) = delete;
BlockQueue& push(const T& value)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.push(value);
//if some threads is wait for taking, notify one.
if(m_waiter_count > 0)
{
m_wait_finished.notify_one();
}
return *this;
}
BlockQueue& push(T&& value)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.push(std::move(value));
//if some threads is wait for taking, notify one.
if(m_waiter_count > 0)
{
m_wait_finished.notify_one();
}
return *this;
}
template<typename... Args>
BlockQueue& emplace(Args&&... args)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.emplace(std::forward<Args>(args)...);
//if some threads is wait for taking, notify one.
if(m_waiter_count > 0)
{
m_wait_finished.notify_one();
}
return *this;
}
T take()
{
std::unique_lock<std::mutex> lock(m_mutex);
if(!m_queue.empty())
{
T value = std::move(const_cast<T&>(m_queue.front()));
m_queue.pop();
return value;
}
if(m_interrupted)
{
throw BlockInterrupt();
}
//if the count of waiter is overflow.
if(m_waiter_count == std::numeric_limits<decltype(m_waiter_count)>::max())
{
throw std::runtime_error("The counter for waiter of block queue is overflow.");
}
//the call must be blocked.
++m_waiter_count;
Final final([this]()
{
//this code will be execute anyhow.
--m_waiter_count;
if(m_waiter_count == 0 && m_interrupted == true)
{
//if count of waiter is zero, and some threads call the interrupt(), notify all.
m_interrupt_finished.notify_all();
}
});
m_wait_finished.wait(lock, [this](){return !m_queue.empty() || m_interrupted;});
if(m_interrupted)
{
throw BlockInterrupt();
}
T value = std::move(const_cast<T&>(m_queue.front()));
m_queue.pop();
return value;
}
bool try_pop(T& value)
{
std::unique_lock<std::mutex> lock(m_mutex);
if(!m_queue.empty())
{
value = std::move(const_cast<T&>(m_queue.front()));
m_queue.pop();
return true;
}
return false;
}
/**
* interrupt all block threads, return until all threads are interrupted.
*/
BlockQueue& interrupt() noexcept
{
std::unique_lock<std::mutex> lock(m_mutex);
if(m_waiter_count == 0)
{
//no waiter, return.
m_interrupted = false;
return *this;
}
m_interrupted = true;
//wake up all block threads.
m_wait_finished.notify_all();
//wait for all threads are interrupted.
m_interrupt_finished.wait(lock, [this](){return m_waiter_count == 0;});
m_interrupted = false;
return *this;
}
private:
/**
* mutex for accessing of "m_queue", "m_interrupted", "m_waiter_count".
*/
std::mutex m_mutex;
std::queue<T> m_queue;
/**
* express whether the queue is interrupted.
*/
bool m_interrupted = false;
/**
* count of threads blocked.
*/
std::uint32_t m_waiter_count = 0;
/**
* condition variable for notifying that the queue is readable or interrupted (so the threads blocked should be awakened).
*/
std::condition_variable m_wait_finished;
/**
* condition variable for notifying that no thread is blocking (so interrupt has finished).
*/
std::condition_variable m_interrupt_finished;
};
int main(int argc, char const *argv[])
{
BlockQueue<int> q;
std::thread taker1([&]()
{
try
{
q.take();
}
catch(const BlockInterrupt&)
{
std::cout << "taker1 interrupted." << std::endl;
}
});
std::thread taker2([&]()
{
try
{
q.take();
}
catch(const BlockInterrupt&)
{
std::cout << "taker2 interrupted." << std::endl;
}
});
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(0.5s);
std::thread interrupter([&]()
{
q.interrupt();
});
taker1.join();
taker2.join();
interrupter.join();
return 0;
}
</code></pre>
<p>thanks for review.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T10:07:26.900",
"Id": "211672",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"queue"
],
"Title": "thread safe queue with interrupt function"
} | 211672 |
<p>I recently wrote a matrix module in C++.</p>
<p>During the development process I quoted some source code and found a problem.</p>
<p>For example, matrix multiplication:</p>
<p>This way is suitable for all <em>N</em>×<em>N</em> matrices:</p>
<pre><code>void multiplyMatrix(const float32* a, const float32* b, float32* dst,
int32 aColumns, int32 bColumns, int32 dstColumns, int32 dstRows) {
for (int32 i = 0; i < dstRows; i++) {
for (int32 j = 0; j < dstColumns; j++)
dst[i * dstColumns + j] = dotMatrix(a, b, aColumns, bColumns, j, i);
}
}
float32 dotMatrix(const float32* a, const float32* b,
int32 aColumns, int32 bColumns,
int32 column, int32 row) {
float32 result = 0.0f;
int32 index = aColumns * row;
for (int32 i = 0; i < aColumns; i++) {
result += a[index++] * b[column];
column += bColumns;
}
return result;
}
</code></pre>
<p>Next, I wrote a 3x3 matrix class.</p>
<pre><code>class Matrix3x3
{
public:
float32 m11, m12, m13,
m21, m22, m23,
m31, m32, m33;
float32 element[9];
void multiply(float32 ma11, float32 ma12, float32 ma13,
float32 ma21, float32 ma22, float32 ma23,
float32 ma31, float32 ma32, float32 ma33) {
float32 temp1 = m11 * ma11 + m21 * ma12 + m31 * ma13;
float32 temp2 = m12 * ma11 + m22 * ma12 + m32 * ma13;
m13 = m13 * ma11 + m23 * ma12 + m33 * ma13;
m11 = temp1;
m12 = temp2;
temp1 = m11 * ma21 + m21 * ma22 + m31 * ma23;
temp2 = m12 * ma21 + m22 * ma22 + m32 * ma23;
m23 = m13 * ma21 + m23 * ma22 + m33 * ma23;
m21 = temp1;
m22 = temp2;
temp1 = m11 * ma31 + m21 * ma32 + m31 * ma33;
temp2 = m12 * ma31 + m22 * ma32 + m32 * ma33;
m31 = m13 * ma31 + m23 * ma32 + m33 * ma33;
m32 = temp1;
m33 = temp2;
}
}
</code></pre>
<p>Obviously the first one is very convenient.</p>
<p>Next, I tested the time it took to calculate:</p>
<pre><code> float32 e1[9];
e1[0] = 2.1018f; e1[1] = -1.81754f; e1[2] = 1.2541f;
e1[3] = 0.54194f; e1[4] = 2.75391f; e1[5] = -0.1167f;
e1[6] = -5.81652f; e1[7] = -7.9381f; e1[8] = 4.2816f;
float32 e2[9];
e2[0] = 2.1018f; e2[1] = -1.81754f; e2[2] = 1.2541f;
e2[3] = 0.54194f; e2[4] = 2.75391f; e2[5] = -0.1167f;
e2[6] = -5.81652f; e2[7] = -7.9381f; e2[8] = 4.2816f;
Matrix3x3 a;
a.m11 = 2.1018f; a.m12 = -1.81754f; a.m13 = 1.2541f;
a.m21 = 0.54194f; a.m22 = 2.75391f; a.m23 = -0.1167f;
a.m31 = -5.81652f; a.m32 = -7.9381f; a.m33 = 4.2816f;
Matrix3x3 b = a;
float64 timeSpent = 0;
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
QueryPerformanceFrequency(&nFreq); // statistical frequency
QueryPerformanceCounter(&nBeginTime);// start timer
for (int32 i = 0; i < 100000; i++) {
multiplyMatrix(e1, e2, dst, 3, 3, 3, 3);
}
QueryPerformanceCounter(&nEndTime); //end timer
timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart);
printf("timeSpent1:%f\n", timeSpent);
QueryPerformanceCounter(&nBeginTime);
for (int32 i = 0; i < 100000; i++) {
b.multiply(a.m11, a.m12, a.m13,
a.m21, a.m22, a.m23,
a.m31, a.m32, a.m33);
}
QueryPerformanceCounter(&nEndTime);
timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart);
printf("timeSpent2:%f\n", timeSpent);
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>timeSpent1:0.014277
timeSpent2:0.004649
timeSpent1:0.012684
timeSpent2:0.004522
.......
.......
timeSpent1:0.003414
timeSpent2:0.001166
timeSpent1:0.003407
timeSpent2:0.001242
</code></pre>
<p>Is this difference in efficiency significant or negligible?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T10:49:11.557",
"Id": "409321",
"Score": "0",
"body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T11:13:11.620",
"Id": "409326",
"Score": "0",
"body": "Which C++ version is this targeting? C++11 or newer? C++98? This might be important context for reviewers since a lot changed since C++98."
}
] | [
{
"body": "<p>A factor 4 for 3x3 is in the same order, and okay.</p>\n\n<p>One could write could to generate a <code>Matrix99x99</code> C++ file, and test that.\nMy guess it would be factor 4 too. If it could be 2 then, and as such it would be totally fine.</p>\n\n<p><em>A remark</em> Normal matrix multiplication A.B with A having dimensions LxM and B dimensions MxN, requiring a s´hared M, resulting in a dimension LxN. So a small C++ class as such would be nice._</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T03:42:01.540",
"Id": "409566",
"Score": "0",
"body": "Sorry, my English is very poor, so using a translator, your suggestion is to write a class or method that handles all NXN matrices? Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-21T07:35:19.293",
"Id": "409753",
"Score": "0",
"body": "Yes, storing the dimensions too would be something for a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-24T10:00:53.213",
"Id": "410213",
"Score": "0",
"body": "But there are some gaps in efficiency, especially for the Minors, cofactors and adjugate inverse matrices, which are 30-40 times slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-24T11:17:59.023",
"Id": "410216",
"Score": "0",
"body": "One can always add heuristics: `if (dimension == 3) { do something special }`. The only overhead then are the indirections, loops not being rolled out and the if-s. I would expect a factor 3 at most. BTW I like harolds answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T12:02:52.790",
"Id": "211682",
"ParentId": "211673",
"Score": "1"
}
},
{
"body": "<p>A factor of 3 is large, but in my opinion not unexpected or abnormal. The functions that can handle a variable size matrix in their natural form (ie as they would be compiled without knowledge of the size, for example if the functions are defined in a different compilation unit than they are used in and LTO is not applied) have a lot of overhead: non-linear control flow (3 nested loops), more complicated address computation (involving multiplication by a variable).</p>\n\n<p>Basically, that is the cost of generality .. but there is more to it.</p>\n\n<p>From your use of QueryPerformanceCounter I assume you use MSVC (other compilers aren't much different for the following considerations). MSVC likes to unroll loops such as the one in <code>dotMatrix</code> by 4. It does not like to unroll such loops by 3, though it can be persuaded to do so anyway, for example by giving it a loop that makes exactly 3 iterations. So the cost of generality would work out much differently if the relevant matrix was of size 4x4 or 8x8, as in those cases only the faster unrolled codepath would be used (this still comes with overhead, but less). 3 is a bad case, only ever using the fallback codepath.</p>\n\n<p>Additionally, the general matrix multiply implemented by <code>multiplyMatrix</code> is not scalable: it does not implement cache blocking, so for any matrix that does not fit in L1 cache it will perform badly (and even more badly when going beyond the L2 and L3 sizes). That is normal for code in general, but matrix multiplication is special in that it does not have to suffer significantly from that common effect thanks to its \"O(n<sup>2</sup>) data in O(n<sup>3</sup>) time\" property.</p>\n\n<p>Both the general matrix multiply and the special 3x3 one could use SIMD intrinsics for extra efficiency. 3x3 is an awkward size that would cause some \"wasted lanes\", but it would still help. For example, it could be done like this (not tested):</p>\n\n<pre><code>#include <xmmintrin.h>\n\nclass Matrix3x3\n{\npublic:\nfloat32 m11, m21, m31, \n m12, m22, m32, \n m13, m23, m33, padding;\n\nvoid multiply(float32 ma11, float32 ma12, float32 ma13,\n float32 ma21, float32 ma22, float32 ma23,\n float32 ma31, float32 ma32, float32 ma33) {\n\n __m128 col1 = _mm_loadu_ps(&m11);\n __m128 col2 = _mm_loadu_ps(&m12);\n __m128 col3 = _mm_loadu_ps(&m13);\n __m128 t1 = _mm_add_ps(_mm_add_ps(\n _mm_mul_ps(col1, _mm_set1_ps(ma11)),\n _mm_mul_ps(col2, _mm_set1_ps(ma21))),\n _mm_mul_ps(col3, _mm_set1_ps(ma31)));\n __m128 t2 = _mm_add_ps(_mm_add_ps(\n _mm_mul_ps(col1, _mm_set1_ps(ma12)),\n _mm_mul_ps(col2, _mm_set1_ps(ma22))),\n _mm_mul_ps(col3, _mm_set1_ps(ma32)));\n __m128 t3 = _mm_add_ps(_mm_add_ps(\n _mm_mul_ps(col1, _mm_set1_ps(ma13)),\n _mm_mul_ps(col2, _mm_set1_ps(ma23))),\n _mm_mul_ps(col3, _mm_set1_ps(ma33)));\n\n _mm_storeu_ps(&m11, t1);\n _mm_storeu_ps(&m12, t2);\n _mm_storeu_ps(&m13, t3);\n}\n};\n</code></pre>\n\n<p>The <code>padding</code> is a bit unfortunate (and shouldn't be private, because that makes its positioning relative to the actual matrix elements undefined), but simplifies the SIMD logic, chunks of 16 bytes are easier to deal with. It is possible to avoid the padding if required. Anyway, this results in a <a href=\"https://gcc.godbolt.org/z/2YUHOy\" rel=\"nofollow noreferrer\">significant reduction in code</a> and should be more efficient (without AVX the <code>set1</code>s cost more, that shouldn't be enough to undo the improvement but I didn't try it). The dllexport in the code on godbolt is not really part of the code, I just put that there to force code to be generated for an otherwise unused method.</p>\n\n<p>Column-major order is used here because the columns of the result are a linear combination of the columns of the left hand matrix, which we have access to in packed memory. Similarly, the rows of the output are a linear combination of the rows of the right hand side, but we have no packed access to the rows of the right hand side, so they would be inefficient to gather. A row-oriented version of the above could be arranged for example if the right hand side was passed in as a reference to a <code>Matrix3x3</code>.</p>\n\n<p>Passing the right hand side as matrix is probably a nicer interface anyway, with 9 separate arguments there is no choice but to write them all out separately even if the RHS is available as a matrix object, as you already experienced in your benchmark code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T03:38:36.487",
"Id": "409565",
"Score": "0",
"body": "Thank you,I don't know assembly language. I read some open source code such as btMatrix3x3.h for bullet3, b2Math.h for Box2D, and some examples of openGL such as matrixModelView. It has been found that in most cases the corresponding matrix is treated separately, such as writing a separate class or method for matrix 3x3 or matrix 4x4 instead of processing all NXN matrices in general, for efficiency? What's your opinion? Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-19T07:44:33.917",
"Id": "409570",
"Score": "0",
"body": "@Shuang2019 yes, specialized classes for specific matrix sizes are more efficient"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:00:31.540",
"Id": "211696",
"ParentId": "211673",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211696",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T10:08:56.733",
"Id": "211673",
"Score": "0",
"Tags": [
"c++",
"performance",
"matrix"
],
"Title": "Multiplication of 3×3 and N×N square matrices"
} | 211673 |
<p>I am trying to design some classes which I intent to use as a framework. I would like them to be compliant to SOLID design principles.</p>
<p>I had a basic structure and then I implemented Strategy design pattern and tried adding dependency injection as well.</p>
<p>Would like this to be reviewed so that I know if my understanding is correct or can still be made better.</p>
<pre><code>public interface IBrowser
{
IWebDriver GetWebDriver(string webDriverFolderPath);
}
public class EdgeBrowser : IBrowser
{
public IWebDriver GetWebDriver(string webDriverFolderPath)
{
var options = new EdgeOptions()
{
PageLoadStrategy = PageLoadStrategy.Eager,
UseInPrivateBrowsing = true
};
return new EdgeDriver(webDriverFolderPath, options, TimeSpan.FromSeconds(60));
}
}
public class IEBrowser : IBrowser
{
public IWebDriver GetWebDriver(string webDriverFolderPath)
{
var options = new InternetExplorerOptions()
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true
};
return new InternetExplorerDriver(webDriverFolderPath, options, TimeSpan.FromSeconds(60));
}
}
public interface IConfiguration
{
string GetConfiguration(string key);
}
public class AppSettingsConfiguration : IConfiguration
{
public string GetConfiguration(string key)
{
return ConfigurationManager.AppSettings[key].ToString();
}
}
public class WebDriver
{
private static Dictionary<Enums.Browsers, IBrowser> Browsers = new Dictionary<Enums.Browsers, IBrowser>();
private static Dictionary<string, Enums.Browsers> BrowserMapper = new Dictionary<string, Enums.Browsers>();
private static AppSettingsConfiguration _AppSettingsConfiguration;
static WebDriver()
{
Browsers.Add(Enums.Browsers.Edge, new EdgeBrowser());
Browsers.Add(Enums.Browsers.IE, new IEBrowser());
Browsers.Add(Enums.Browsers.Chrome, new ChromeBrowser());
Browsers.Add(Enums.Browsers.Firefox, new FirefoxBrowser());
BrowserMapper.Add("Edge", Enums.Browsers.Edge);
BrowserMapper.Add("IE", Enums.Browsers.IE);
BrowserMapper.Add("Internet Explorer", Enums.Browsers.IE);
BrowserMapper.Add("Chrome", Enums.Browsers.Chrome);
BrowserMapper.Add("Firefox", Enums.Browsers.Firefox);
BrowserMapper.Add("edge", Enums.Browsers.Edge);
BrowserMapper.Add("ie", Enums.Browsers.IE);
BrowserMapper.Add("internet explorer", Enums.Browsers.IE);
BrowserMapper.Add("chrome", Enums.Browsers.Chrome);
BrowserMapper.Add("firefox", Enums.Browsers.Firefox);
BrowserMapper.Add("internetexplorer", Enums.Browsers.IE);
BrowserMapper.Add("InternetExplorer", Enums.Browsers.IE);
}
public WebDriver(AppSettingsConfiguration appSettingsConfiguration)
{
_AppSettingsConfiguration = appSettingsConfiguration;
}
public IWebDriver GetWebDriver(string browser)
{
var browserName = BrowserMapper[browser];
return Browsers[browserName].GetWebDriver(_AppSettingsConfiguration.GetConfiguration("WebDriverFolderPath"));
}
}
public void Initialize()
{
if (WebDriver == null)
{
WebDriver = new WebDriver(new AppSettingsConfiguration()).GetWebDriver(BaseData.Browser);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:22:41.533",
"Id": "409342",
"Score": "0",
"body": "Perhaps `GetWebDriver()` could just use the `Browsers` enumeration to avoid having to create duplicate mappings like `\"internetexplorer\", \"InternetExplorer\", and \"internet explorer\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:50:03.750",
"Id": "409345",
"Score": "0",
"body": "@Shelby115 thanks for the reply. Initialize method receives data read from an excel. So browser name can vary and I was not able to think about any other way to map user input to enums..."
}
] | [
{
"body": "<p>I'm not really sure that there is any good argument having these static fields, especially when it comes to unit testing the <code>WebDriver</code> class.</p>\n\n<pre><code>public class WebDriver\n{\n private static Dictionary... // this\n private static Dictionary... // this\n private static AppSetting... // this\n\n static WebDriver() // this\n {\n ...\n }\n\n ...\n}\n</code></pre>\n\n<p>I would suggest you change those to <code>private readonly</code> fields instead.</p>\n\n<p>and then we have this <code>Initialize()</code> method hanging out on it's own -- which means your code could not compile as is.</p>\n\n<pre><code>public class Foo // where is the class?\n{\n public void Initialize()\n {\n if (WebDriver == null)\n {\n WebDriver = new WebDriver(new AppSettingsConfiguration())\n .GetWebDriver(BaseData.Browser);\n }\n }\n}\n</code></pre>\n\n<p>I highly would not recommend passing around the <code>AppSettingsConfiguration</code> class, when it seems like the only time you use it is to pull a string value by calling <code>_AppSettingsConfiguration.GetConfiguration(\"WebDriverFolderPath\")</code>.</p>\n\n<p>It would make more sense for you to handle reading your configuration somewhere else and not make the <code>WebDriver</code> responsible for handling that... (This actually breaks your \"S\" in the SOLID principle).</p>\n\n<p>I would probably advise to consider refactoring it along these lines...</p>\n\n<pre><code>public enum Browsers { Unknown, Ie, Chrome, Edge, FireFox }\n\npublic class WebDriverFactory\n{\n private readonly string _path;\n\n public WebDriverFactory(string path)\n {\n if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));\n // also, consider to a check that the path exists\n\n _path = path;\n }\n\n public IWebDriver Construct(Browsers browser)\n {\n switch (browser)\n {\n case Browser.Edge:\n {\n var options = new EdgeOptions()\n {\n PageLoadStrategy = PageLoadStrategy.Eager,\n UseInPrivateBrowsing = true\n };\n return new EdgeDriver(_path, options, TimeSpan.FromSeconds(60));\n }\n case.Unknown:\n throw new Exception(\"not a valid browser\");\n default:\n throw new NotImplementedException();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:06:25.540",
"Id": "211700",
"ParentId": "211676",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T11:15:27.980",
"Id": "211676",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"webdriver",
"cross-browser"
],
"Title": "Reusable webdriver framework using SOLID design principles"
} | 211676 |
<p>So I've been working on a generator for Pascal's triangle in Python. Now, I wouldn't call myself a Python god, so my program is a lot longer than the very confusing ones on the internet. It's more of a logical approach to creating the triangle.</p>
<p>Here's the program:</p>
<pre><code>def double_chunker(lst):
leng = len(lst)
for i in range(leng):
if i == 0:
yield [lst[0]]
elif i == 1:
yield [lst[0], lst[1]]
elif i == leng:
yield [lst[-1]]
else:
yield [lst[i-1], lst[i]]
yield [lst[-1]]
def chunk_adder(lst):
for i in lst:
if len(i) == 1:
yield i[0]
else:
yield sum(i)
def pascal_next(lst):
return list(chunk_adder(double_chunker(lst)))
def pascal_triangle(rows):
end = [[1]]
for i in range(rows):
end.append(pascal_next(end[-1]))
return end
</code></pre>
<p>A simple go-through of how it works:</p>
<ol>
<li><p><code>double_chunker()</code> splits up a row of Pascal's triangle into the pairs of numbers you would use when adding up to determine the numbers in the next row. This algorithm is little <em>jerry-rigged</em> - I had to add some special exceptions for some numbers on the end of the row to make it work properly.</p></li>
<li><p><code>chunk_adder()</code> adds together a list of chunks generated by <code>double_chunker</code> to determine the next row in the Pascal sequence.</p></li>
<li><p><code>pascal_next()</code>combines both <code>double_chunker()</code> and <code>chunk_adder()</code> to, when given one row in Pascal's triangle, determine the next row in the triangle.</p></li>
<li><p><code>pascal_triangle()</code> iteratively creates rows of Pascal's triangle using <code>pascal_next()</code>.</p></li>
</ol>
<p>So, here are some of my questions:</p>
<ol>
<li><p>Is there anything in my program that seems redundant, repetitive, or can be shortened?</p></li>
<li><p>Is there any better code practices I should be employing and am not?</p></li>
</ol>
<p>And obviously, as always, feel free to provide any other feedback you may have. Thanks in advance!</p>
| [] | [
{
"body": "<p><strong>Names</strong></p>\n\n<p>I am not fully convinced by the different function names but I have nothing better to suggest for the time being.</p>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide called PEP 8</a>. It is an interesting read. The most significant impact for your code would be to use 4 spaces for each indentation level instead of 2.</p>\n\n<p><strong>Simplify <code>double_chunker</code></strong></p>\n\n<p>In <code>double_chunker</code>, the following condition is never true:</p>\n\n<pre><code>elif i == leng:\n yield [lst[-1]]\n</code></pre>\n\n<p>Also, you don't need to handle explicitly the case:</p>\n\n<pre><code>elif i == 1:\n yield [lst[0], lst[1]]\n</code></pre>\n\n<p>as it is just a particular case for <code>[lst[i-1], lst[i]]</code> with <code>i == 1</code>.</p>\n\n<p><strong>Simplify <code>chunk_adder</code></strong></p>\n\n<p>In <code>chunk_adder</code>, instead of:</p>\n\n<pre><code>if len(i) == 1:\n yield i[0]\nelse:\n yield sum(i)\n</code></pre>\n\n<p>We can write:</p>\n\n<pre><code>yield sum(i)\n</code></pre>\n\n<p>Then, we could rewrite the function using generator expressions:</p>\n\n<pre><code>def chunk_adder(lst):\n return (sum(i) for i in lst)\n</code></pre>\n\n<p>Then, it looks like the function is not really needed. We could write:</p>\n\n<pre><code>def pascal_next(lst):\n return [sum(i) for i in double_chunker(lst)]\n</code></pre>\n\n<hr>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def double_chunker(lst):\n for i in range(len(lst)):\n if i == 0:\n yield [lst[0]]\n else:\n yield [lst[i-1], lst[i]]\n yield [lst[-1]]\n\n\ndef pascal_next(lst):\n return [sum(i) for i in double_chunker(lst)]\n\ndef pascal_triangle(rows):\n end = [[1]]\n for i in range(rows):\n end.append(pascal_next(end[-1]))\n return end\n\n\nprint(pascal_triangle(8))\n</code></pre>\n\n<p><strong>More simplification in <code>double_chunker</code></strong></p>\n\n<p>We could handle the case <code>i == 0</code> before the loop rather than inside the loop. That could lead to a slightly different behavior when the input is an empty list but that case is not handled properly anyway (exception thrown).</p>\n\n<pre><code>def double_chunker(lst):\n yield [lst[0]]\n for i in range(1, len(lst)):\n yield [lst[i-1], lst[i]]\n yield [lst[-1]]\n</code></pre>\n\n<p>Then, it becomes obvious what we want to do: we want to <a href=\"https://stackoverflow.com/questions/21303224/iterate-over-all-pairs-of-consecutive-items-in-a-list\">iterate over all pairs of consecutive items in a list</a> which is a problem common enough to find various solutions to it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T13:22:26.557",
"Id": "211684",
"ParentId": "211677",
"Score": "5"
}
},
{
"body": "<blockquote>\n<pre><code>def chunk_adder(lst):\n for i in lst:\n if len(i) == 1:\n yield i[0]\n else:\n yield sum(i)\n</code></pre>\n</blockquote>\n\n<p><code>sum</code> can happilly consume iterable of size 1, it can even consume iterable of size 0:</p>\n\n<pre><code>>>> sum([1])\n1\n>>> sum([])\n0\n</code></pre>\n\n<p>So you can simplify it to:</p>\n\n<pre><code>def chunck_adder(iterable):\n for element in iterable:\n yield sum(element)\n</code></pre>\n\n<p>Which is simply</p>\n\n<pre><code>def chunck_adder(iterable):\n yield from map(sum, iterable)\n</code></pre>\n\n<p>So you could simplify <code>pascal_next</code> instead:</p>\n\n<pre><code>def pascal_next(lst):\n return list(map(sum, double_chunker(lst)))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>def double_chunker(lst):\n leng = len(lst)\n for i in range(leng):\n if i == 0:\n yield [lst[0]]\n elif i == 1:\n yield [lst[0], lst[1]]\n elif i == leng:\n yield [lst[-1]]\n else:\n yield [lst[i-1], lst[i]]\n yield [lst[-1]]\n</code></pre>\n</blockquote>\n\n<p>The intent is pretty much the same than the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>pairwise</code> recipe</a> from <code>itertools</code>. Except you want to yield the first and last element as well.</p>\n\n<p>Here you have two possibilities:</p>\n\n<ul>\n<li><p>either yield them manually:</p>\n\n<pre><code>import itertools\n\ndef double_chunker(lst):\n if not lst:\n return\n a, b = itertools.tee(lst)\n next(b, None)\n\n yield [lst[0]]\n yield from zip(a, b)\n yield [lst[-1]]\n</code></pre>\n\n<p>But this forces the argument to be a list, or at least to know if its empty and to implement <code>__getitem__</code>.</p></li>\n<li><p>or add boundary values to your input so <code>pairwise</code> can work properly:</p>\n\n<pre><code>import itertools\n\n\ndef pairwise(iterable):\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef double_chuncker(iterable):\n extended = itertools.chain([0], iterable, [0])\n return pairwise(extended)\n</code></pre>\n\n<p>Which I recommend because it happily consume any iterable.</p></li>\n</ul>\n\n<hr>\n\n<blockquote>\n<pre><code>def pascal_triangle(rows):\n end = [[1]]\n for i in range(rows):\n end.append(pascal_next(end[-1]))\n return end\n</code></pre>\n</blockquote>\n\n<p>Instead of relying on the list being constructed, I would explicitly store the current row. I would also turn this into an infinite generator because it really is and maybe provide an helper function for convenience:</p>\n\n<pre><code>def pascal_triangle():\n row = [1]\n while True:\n yield row\n row = pascal_next(row)\n\n\ndef pascal_triangle_up_to(n):\n return list(itertools.islice(pascal_triangle(), n))\n</code></pre>\n\n<hr>\n\n<p>Full code:</p>\n\n<pre><code>import itertools\n\n\ndef pairwise(iterable):\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef double_chuncker(iterable):\n extended = itertools.chain([0], iterable, [0])\n return pairwise(extended)\n\n\ndef pascal_next(iterable):\n return list(map(sum, double_chuncker(iterable)))\n\n\ndef pascal_triangle():\n row = [1]\n while True:\n yield row\n row = pascal_next(row)\n\n\ndef pascal_triangle_up_to(n):\n return list(itertools.islice(pascal_triangle(), n))\n\n\nif __name__ == '__main__':\n # Testing\n for row in pascal_triangle():\n print(row, end='')\n if (input()):\n break\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T13:23:00.687",
"Id": "211685",
"ParentId": "211677",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p>Is there any better code practices I should be employing and am not?</p>\n</blockquote>\n\n<ul>\n<li>The first thing that caught my attention is the missing tests</li>\n</ul>\n\n<p>You should implement a few test cases to ensure that after changes the program does still work as intended</p>\n\n<p>Both the <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unittest</a> module or <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctest</a> are good Python modules for testing, I have used the <code>unittest</code> as an example</p>\n\n<pre><code>class PascalTriangleTest(unittest.TestCase):\n def test_triangle_0(self):\n self.assertEqual(\n pascal_triangle(0), \n [[1]]\n )\n\n def test_triangle_1(self):\n self.assertEqual(\n pascal_triangle(1), \n [[1], [1, 1]]\n )\n\n def test_triangle_2(self):\n self.assertEqual(\n pascal_triangle(2), \n [[1], [1, 1], [1, 2, 1]]\n )\n\n def test_triangle_3(self):\n self.assertEqual(\n pascal_triangle(3), \n [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]\n )\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n\n<ul>\n<li>The second one would be the missing docstrings</li>\n</ul>\n\n<p>The comments below your code would be a good start to make the docstring for each function. </p>\n\n<p>See <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP257</a>, for docstring conventions</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:19:51.233",
"Id": "211691",
"ParentId": "211677",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Is there anything in my program that seems redundant, repetitive, or can be shortened?</p>\n</blockquote>\n\n<p>The 22 lines of <code>double_chunker</code>, <code>chunk_adder</code>, and <code>pascal_next</code> can be shortened to</p>\n\n<pre><code>def pascal_next(lst):\n return [left + right for (left, right) in zip(lst + [0], [0] + lst)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:47:33.237",
"Id": "409344",
"Score": "1",
"body": "Or `return [sum(pair) for pair in zip(lst + [0], [0] + lst)]` to make use of the built in `sum`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:28:33.273",
"Id": "409351",
"Score": "0",
"body": "@Ludisposed, I deliberately chose not to do that because I regard it as a pessimisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:30:48.380",
"Id": "409352",
"Score": "0",
"body": "You could also omit the parenthesis: `[left + right for left, right in zip(lst + [0], [0] + lst)]`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T14:44:04.477",
"Id": "211694",
"ParentId": "211677",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "211685",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T11:24:51.617",
"Id": "211677",
"Score": "4",
"Tags": [
"python"
],
"Title": "Pascal's Triangle Generator in Python"
} | 211677 |
<p>Following the <a href="https://codereview.stackexchange.com/questions/211622/knuth-morris-pratt-over-a-source-of-indeterminate-length">successful review of my previous implementation</a>.</p>
<p>Please review my new, generic implementation of the <a href="https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm" rel="nofollow noreferrer">Knuth-Morris-Pratt algorithm</a>. Its modified to search a source of indeterminate length in a memory efficient fashion.</p>
<pre><code>namespace Code
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A generic implementation of the Knuth-Morris-Pratt algorithm that searches,
/// in a memory efficient way, over a given <see cref="IEnumerable{T}"/>.
/// </summary>
public static class KMP
{
/// <summary>
/// Determines whether a sequence contains the search string.
/// </summary>
/// <typeparam name="T">
/// The type of elements of <paramref name="source"/>
/// </typeparam>
/// <param name="source">
/// A sequence of elements
/// </param>
/// <param name="pattern">The search string.</param>
/// <param name="equalityComparer">
/// Determines whether the sequence contains a specified element.
/// If <c>null</c>
/// <see cref="EqualityComparer{T}.Default"/> will be used.
/// </param>
/// <returns>
/// <c>true</c> if the source contains the specified pattern;
/// otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">pattern</exception>
public static bool Contains<T>(
this IEnumerable<T> source,
IEnumerable<T> pattern,
IEqualityComparer<T> equalityComparer = null)
{
if (pattern == null)
{
throw new ArgumentNullException(nameof(pattern));
}
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
return SearchImplementation(source, pattern, equalityComparer).Any();
}
public static IEnumerable<long> IndicesOf<T>(
this IEnumerable<T> source,
IEnumerable<T> pattern,
IEqualityComparer<T> equalityComparer = null)
{
if (pattern == null)
{
throw new ArgumentNullException(nameof(pattern));
}
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
return SearchImplementation(source, pattern, equalityComparer);
}
/// <summary>
/// Identifies indices of a pattern string in a given sequence.
/// </summary>
/// <typeparam name="T">
/// The type of elements of <paramref name="source"/>
/// </typeparam>
/// <param name="source">
/// The sequence to search.
/// </param>
/// <param name="patternString">
/// The string to find in the sequence.
/// </param>
/// <param name="equalityComparer">
/// Determines whether the sequence contains a specified element.
/// </param>
/// <returns>
/// A sequence of indices where the pattern can be found
/// in the source.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// patternSequence - The pattern must contain 1 or more elements.
/// </exception>
private static IEnumerable<long> SearchImplementation<T>(
IEnumerable<T> source,
IEnumerable<T> patternString,
IEqualityComparer<T> equalityComparer)
{
// Pre-process the pattern
(var slide, var pattern) = GetSlide(patternString, equalityComparer);
var patternLength = pattern.Count;
if (patternLength == 0)
{
throw new ArgumentOutOfRangeException(
nameof(patternString),
"The pattern must contain 1 or more elements.");
}
var buffer = new Dictionary<long, T>(patternLength);
var more = true;
long sourceIndex = 0; // index for source
int patternIndex = 0; // index for pattern
using(var sourceEnumerator = source.GetEnumerator())
while (more)
{
more = FillBuffer(
buffer,
sourceEnumerator,
sourceIndex,
patternLength,
out T t);
if (equalityComparer.Equals(pattern[patternIndex], t))
{
patternIndex++;
sourceIndex++;
more = FillBuffer(
buffer,
sourceEnumerator,
sourceIndex,
patternLength,
out t);
}
if (patternIndex == patternLength)
{
yield return sourceIndex - patternIndex;
patternIndex = slide[patternIndex - 1];
}
else if (more && !equalityComparer.Equals(pattern[patternIndex], t))
{
if (patternIndex != 0)
{
patternIndex = slide[patternIndex - 1];
}
else
{
sourceIndex = sourceIndex + 1;
}
}
}
}
/// <summary>
/// Services the buffer and retrieves the value.
/// </summary>
/// <remarks>
/// The buffer is used so that it is not necessary to hold the
/// entire source in memory.
/// </remarks>
/// <typeparam name="T">
/// The type of elements of <paramref name="source"/>.
/// </typeparam>
/// <param name="buffer">The buffer.</param>
/// <param name="source">The source enumerator.</param>
/// <param name="sourceIndex">The element index to retrieve.</param>
/// <param name="patternLength">Length of the search string.</param>
/// <param name="value">The element value retrieved from the source.</param>
/// <returns>
/// <c>true</c> if there is potentially more data to process;
/// otherwise <c>false</c>.
/// </returns>
private static bool FillBuffer<T>(
IDictionary<long, T> buffer,
IEnumerator<T> source,
long sourceIndex,
int patternLength,
out T value)
{
bool more = true;
if (!buffer.TryGetValue(sourceIndex, out value))
{
more = source.MoveNext();
if (more)
{
value = source.Current;
buffer.Remove(sourceIndex - patternLength);
buffer.Add(sourceIndex, value);
}
}
return more;
}
/// <summary>
/// Gets the offset array which acts as a slide rule for the KMP algorithm.
/// </summary>
/// <typeparam name="T">
/// The type of elements of <paramref name="source"/>.
/// </typeparam>
/// <param name="pattern">The search string.</param>
/// <param name="equalityComparer">
/// Determines whether the sequence contains a specified element.
/// If <c>null</c>
/// <see cref="EqualityComparer{T}.Default"/> will be used.
/// </param>
/// <returns>A tuple of the offsets and the enumerated pattern.</returns>
private static (IReadOnlyList<int> Slide, IReadOnlyList<T> Pattern) GetSlide<T>(
IEnumerable<T> pattern,
IEqualityComparer<T> equalityComparer)
{
var patternList = pattern.ToList();
var slide = new int[patternList.Count];
int length = 0;
int patternIndex = 1;
while (patternIndex < patternList.Count)
{
if (equalityComparer.Equals(
patternList[patternIndex],
patternList[length]))
{
length++;
slide[patternIndex] = length;
patternIndex++;
}
else
{
if (length != 0)
{
length = slide[length - 1];
}
else
{
slide[patternIndex] = length;
patternIndex++;
}
}
}
return (slide, patternList);
}
}
}
</code></pre>
<p>Below is an example of how this algorithm could be used. Here <a href="https://docs.microsoft.com/en-us/dotnet/api/system.globalization.textelementenumerator?view=netframework-4.7.2" rel="nofollow noreferrer"><code>TextElementEnumerator</code></a> is used with the generic implementation to trivially search Unicode strings with different Unicode Normalizations.</p>
<pre><code>namespace Code
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var decomposed = "ṩ".Normalize(NormalizationForm.FormD);
var composed = "ṩ".Normalize(NormalizationForm.FormKC);
var testData = new List<(string Source, string Pattern)>
{
(string.Empty, composed),
($"y", composed),
($"{decomposed}", composed),
($"y{decomposed}", composed),
($"{decomposed}y", composed),
($"a{composed}{decomposed}{composed}b",
$"{composed}{decomposed}{composed}"),
($"aabab{decomposed}bcc", $"ab{composed}"),
};
foreach (var d in testData)
{
var contains = Ext.Contains(
d.Source,
d.Pattern,
StringComparer.InvariantCultureIgnoreCase);
Console.WriteLine(
$"Source:\"{d.Source}\", Pattern:\"{d.Pattern}\", Contains:({contains})");
}
Console.ReadKey();
}
}
public static class Ext
{
public static bool Contains(
this string source,
string value,
StringComparer comparer = null)
{
comparer = comparer ?? StringComparer.Ordinal;
return GetTextElements(source).Contains(GetTextElements(value), comparer);
}
private static IEnumerable<string> GetTextElements(string source)
{
var enumerator = StringInfo.GetTextElementEnumerator(source);
while (enumerator.MoveNext())
{
yield return enumerator.GetTextElement();
}
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T12:39:48.553",
"Id": "211683",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"strings",
"search"
],
"Title": "Improved Knuth-Morris-Pratt over a source of indeterminate length"
} | 211683 |
<p>This snippet allows to up and down TCP server via Flask endpoints. I'm seriously concerned about global variables here. And asking for review this code.</p>
<p>The main idea is to be able to up/down TCP server by request to the Flask web service, we need it for testing purposes.</p>
<pre><code>import socket
from flask import Flask
import threading
# tcp server
TCP_IP = '0.0.0.0'
TCP_PORT = 5001
BUFFER_SIZE = 20
# flask app
app = Flask(__name__)
light_on = False
thread_on = False
thread = False
def launchServer():
def run():
global light_on
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
print("run", flush=True)
print('waiting for connection', flush=True)
CONN, addr = s.accept()
while light_on:
print('Connection address:', addr, flush=True)
# Logic Here
CONN.shutdown(socket.SHUT_RDWR)
CONN.close()
global thread
if thread_on:
thread = threading.Thread(target=run)
thread.start()
@app.route('/start')
def start():
print('starting', flush=True)
global light_on
global thread_on
light_on = True
thread_on = True
launchServer()
return "Started"
@app.route('/stop')
def stop():
global light_on
global thread
global thread_on
light_on = False
thread_on = False
thread.do_run = False
thread.join()
return "Stopped"
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=5000, use_reloader=False, threaded=True)
</code></pre>
<p>Is there a best way for it, or can I avoid global variables, and be sure that the code thread safe? </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T13:54:42.157",
"Id": "211687",
"Score": "1",
"Tags": [
"python",
"tcp",
"flask"
],
"Title": "Flask app for control TCP server"
} | 211687 |
<p><strong>Question-</strong>
<a href="https://i.stack.imgur.com/D6UTV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D6UTV.png" alt="enter image description here"></a></p>
<p><strong>My approach</strong> </p>
<p>I noticed that the minimum of a row is when t=k-one of the numbers of that row.
Suppose in the above sample case,
t=4 which is 6-2.
Since we have to find the minimum maximum testing all k-no will give the solution.
Any tips to improve this technique as for cases where each number is unique and number of rows is high this will become slow?</p>
<ul>
<li><code>plus</code> stores unique k-no</li>
<li><code>curmax</code> stores the current maximum for the current 't'.</li>
<li><code>ans</code> is the minimum of all those maximums.</li>
</ul>
<p><strong>Code</strong></p>
<pre><code>#include<iostream>
#include<set>
using namespace std;
int main()
{
set<int>plus;
int n,k;
cin>>n>>k;
int a[n],b[n],c[n];
for(int i=0;i<n;i++)
{
cin>>a[i]>>b[i]>>c[i];
plus.insert(k-a[i]);
plus.insert(k-b[i]);
plus.insert(k-c[i]);
}
int ans=1000000000,curmax=-1,tempsum;
for(auto x:plus)
{
curmax=-1;
for(int i=0;i<n;i++)
{
tempsum=(a[i]+x)%k+(b[i]+x)%k+(c[i]+x)%k;
if(tempsum>curmax)
curmax=tempsum;
}
if(curmax<ans)
ans=curmax;
}
cout<<ans;
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:03:41.410",
"Id": "211697",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"programming-challenge"
],
"Title": "Finding minimum of a function dependent on a constant number"
} | 211697 |
<p>I have written a solution to a <a href="https://dmoj.ca/problem/bf3" rel="nofollow noreferrer">DM::OJ exercise</a> to find the next Prime Number after a given number (input). I'm seeking to optimize it so that it will run for any number up to <code>1000000000</code> in 2 seconds or less. </p>
<p>Here is my code: </p>
<pre><code>from functools import reduce
num = int(input())
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
f = (factors(num))
if (len(f) != 2):
while (len(f) != 2):
num += 1
f = factors(num)
print (num)
else:
print (num)
</code></pre>
<p>Just as a side note, I also found another way to execute this exact same thing, but that one is slower, so I wouldn't mind bothering with that way. However, just for reference though, I'm still adding the slow one anyways: </p>
<pre><code>num = int(input())
def factors(x):
a = []
for i in range(1, x + 1):
if x % i == 0:
a.append(i)
return a
f = (factors(num))
if (len(f) != 2):
while (len(f) != 2):
num += 1
f = factors(num)
print (num)
else:
print (num)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:03:23.317",
"Id": "409379",
"Score": "1",
"body": "Welcome to Code Review! I was attempting to view the repl.it link but it yielded a 404. On [your list of (public) repls](https://repl.it/@AriAri) I see [Next Prime](https://repl.it/@AriAri/Next-Prime). Is there one called _Next Prime Way 2_ that is not private?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:06:13.983",
"Id": "409380",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ No, it's just that I deleted the repl, because the problem was solved."
}
] | [
{
"body": "<pre><code>if (len(f) != 2): \n while (len(f) != 2): \n num += 1\n f = factors(num)\n print (num)\nelse: \n print (num)\n</code></pre>\n\n<p>In places where you use both <code>if</code> and <code>while</code>, they can usually be collapsed into a single <code>while</code>. You can think of an <code>if</code> as a single use <code>while</code>. In your first <code>if</code> block, the final <code>print(num)</code> would only get executed once <code>len(f)</code> becomes 2, so it can just be left outside of the while loop. Which will make something like this:</p>\n\n<pre><code>while (len(f) != 2): \n num += 1\n f = factors(num)\nprint (num)\n</code></pre>\n\n<hr>\n\n<p>As for ways of speeding up, you could consider keeping a list of previous primes and only dividing by those. That will cut down on the comparisons in the factor search. It might require some prior calculation, but the next calculations will be faster.</p>\n\n<p>Another thing that could help is taking steps bigger than +1 while looking for the next prime. We know that all even numbers bigger than 2 are not prime, for example, and also that all numbers divisible by 3 that are bigger than 3 are not prime. So out of every 6 numbers, only two are possibly prime. If we use a counter variable <code>n</code>, then <code>6n</code>, <code>6n+2</code>, <code>6n+3</code>, and <code>6n+4</code> are definitely not prime, so you could just check <code>6n+1</code> and <code>6n+5</code>. Although that would require rearranging some of your program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:09:21.220",
"Id": "409368",
"Score": "0",
"body": "Thanks. Will keep those tips in mind. P.S: It worked!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:07:58.277",
"Id": "211701",
"ParentId": "211699",
"Score": "3"
}
},
{
"body": "<p>There are a lot of <a href=\"https://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow noreferrer\">primality tests</a> out there. Calculating all factors and then checking the length of that list to be 2 is one of the slower ones.</p>\n\n<p>A faster one is just to test if any number smaller than <span class=\"math-container\">\\$\\sqrt{n}\\$</span> divides the number evenly. If it does, the number is not prime and you can move on to the next number:</p>\n\n<pre><code>from math import sqrt\n\ndef is_prime(n):\n if n in (2, 3, 5, 7, 11): # special case small primes\n return True\n if n % 2 == 0 or n == 1: # special case even numbers and 1\n return False\n for i in range(3, int(sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n</code></pre>\n\n<p>Then you can get all numbers starting with <code>num</code> using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow noreferrer\"><code>itertools.count</code></a> and skip all which are not prime using <code>filter</code>:</p>\n\n<pre><code>from itertools import count\n\nif __name__ == \"__main__\":\n num = int(input())\n next_prime = next(filter(is_prime, count(num)))\n print(next_prime)\n</code></pre>\n\n<p>For the upper bound of <span class=\"math-container\">\\$2\\cdot 10^9\\$</span> given in the problem statement this takes about 2ms on my machine.</p>\n\n<p>If this was not fast enough you could first have run a probabilistic test like <a href=\"https://en.wikipedia.org/wiki/Primality_test#Miller%E2%80%93Rabin_and_Solovay%E2%80%93Strassen_primality_test\" rel=\"nofollow noreferrer\">Miller-Rabin</a> to weed out some composite numbers and only run this for the once passing it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T18:05:46.387",
"Id": "211713",
"ParentId": "211699",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211701",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T15:57:18.060",
"Id": "211699",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "The next prime number in Python"
} | 211699 |
<p>Somebody asked me to create a code that orders unique numbers of an array according to their frequency, ie:</p>
<pre><code>{1,3,3,4,4,4,4,4,2,2,5,5,5,5}
</code></pre>
<p>to</p>
<pre><code>{4,5,3,2,1}
</code></pre>
<p>I'm a beginner and only started learning C last week so my code probably isn't optimal. I managed to get it in just over 100 lines without worrying too much about space. I haven't messed with memory allocation yet but I should start looking into it.</p>
<p>Any tips or feedback?</p>
<pre><code>#include <stdio.h>
#include <string.h>
void CalculateFrequency(int numbers[], int frequency[]) //Populates an array with the frequency of numbers in another
{
int hasSorted = 0;
do
{
hasSorted = 0;
for(int currentInt=0; currentInt<10; currentInt++)
{
for(int i=0; i<10; i++)
{
if(numbers[i] == currentInt)
{
frequency[currentInt]++;
hasSorted = 1;
}
}
}
if(hasSorted == 0)
{
break;
}
}while(hasSorted == 0);
}
void SortByFrequency(int numbers[], int frequency[]) //Sorts an array according to the frequency of the numbers
{
int hasSorted = 0;
int temp = 0;
do
{
hasSorted = 0;
for(int i=0; i<10; i++)
{
for(int i=0; i<10; i++)
{
if(frequency[numbers[i]] < frequency[numbers[i+1]])
{
temp = numbers[i+1];
numbers[i+1] = numbers[i];
numbers[i] = temp;
hasSorted = 1;
}
}
}
if(hasSorted == 0)
{
break;
}
}while(hasSorted == 0);
}
int CountUniqueNumbers(int array[], int arrayLength) //Counts unique numbers in an array
{
int count = 1; //At least 1 number
for(int i=0; i<arrayLength-1; i++)
{
if(array[i] != array[i+1])
{
count++;
}
}
return count;
}
int PopulateArrayByFrequencyAndReturnLength(int numbers[], int sortedByFrequency[])
{
int k = 0;
sortedByFrequency[0] = numbers[0];
for(int i=0; i<10; i++)
{
if(numbers[i] != numbers[i+1])
{
sortedByFrequency[k] = numbers[i];
k++;
}
}
return k;
}
int counter;
int main(void)
{
int numbers[10] = {1,2,2,2,5,7,8,8,8,8};
int frequency[10] = {0,0,0,0,0,0,0,0,0,0};
int sortedByFrequency[10] = {0,0,0,0,0,0,0,0,0,0};
int sortedByFrequencyTrueLength = 0;
int differentNumbers = 1; /*The array must have at least 1 number*/
int sizeofNumbersArray = 10;
int uniqueNumbersInArray = 0;
int i = 0;
/*print the numbers*/
printf("Numbers:\t");
for(int i=0; i<10; i++)
{
printf("%d ", numbers[i]);
}
puts("");
/*Perform functions*/
CalculateFrequency(numbers, frequency);
SortByFrequency(numbers, frequency);
/*Get amount of unique numbers in the array*/
uniqueNumbersInArray = CountUniqueNumbers(numbers, sizeofNumbersArray);
/*Poupulate the unique number frequency array and get the true length*/
sortedByFrequencyTrueLength = PopulateArrayByFrequencyAndReturnLength(numbers, sortedByFrequency);
//Print unique number frequency array
printf("Numbers sorted by frequency:\t");
for(i=0; i<sortedByFrequencyTrueLength; i++)
{
printf("%d ", sortedByFrequency[i]);
}
puts("");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:54:26.883",
"Id": "409389",
"Score": "2",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (**if it would constitute a code review**) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T20:44:31.853",
"Id": "409406",
"Score": "0",
"body": "What should happen if there is a tie?"
}
] | [
{
"body": "<p>I see a couple occurrences of:</p>\n\n<pre><code>do\n{\n hasSorted = 0;\n ...other things...\n if(hasSorted == 0)\n {\n break;\n }\n}while(hasSorted == 0);\n</code></pre>\n\n<p>Did you mean <code>if(hasSorted == 1)</code> in those? If not, then you might want to just get rid of the whole if statement and replace the while condition with <code>while(hasSorted != 0)</code>.</p>\n\n<hr>\n\n<p>Also, comments that describe the whole function could look better on a separate line right before the function, so that the line doesn't get too long. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:17:03.847",
"Id": "409382",
"Score": "0",
"body": "Yes the break was redundant! Thanks for pointing that out!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:50:56.717",
"Id": "211707",
"ParentId": "211702",
"Score": "5"
}
},
{
"body": "<p>A few things I noticed:</p>\n\n<p><strong>Unused variables</strong><br>\nThe variables</p>\n\n<ul>\n<li><code>differentNumbers</code></li>\n<li><code>sizeofNumbersArray</code></li>\n<li><code>uniqueNumbersInArray</code></li>\n</ul>\n\n<p>are never used. That is particularly interesting because <code>uniqueNumbersInArray</code> is the return value of the function <code>CountUniqueNumbers</code>. Which means, that function is called for naught. As a matter of fact, the function <code>PopulateArrayByFrequencyAndReturnLength</code> returns the very same value!</p>\n\n<p><strong>Exceeding array bounds</strong><br>\nOn several occasions you access the arrays beyond their limits. As a first example, the function <code>PopulateArrayByFrequencyAndReturnLength</code>.</p>\n\n<pre><code>for(int i = 0; i < 10; i++)\n{\n if(numbers[i] != numbers[i+1])\n {\n sortedByFrequency[k] = numbers[i];\n k++;\n }\n}\n</code></pre>\n\n<p>The index <code>i</code> runs all the way up to the last index, but the if accesses <code>numbers[i+1]</code>, the element to the right. At the very last iteration you access <code>numbers[10]</code>, the 11th element, but <code>numbers</code> is only 10 in length.</p>\n\n<p>The same thing (for the same reasons) happens in <code>SortByFrequency</code>.</p>\n\n<p><strong>Logical errors</strong><br>\nRunning off the end of the array is the reason the function <code>PopulateArrayByFrequencyAndReturnLength</code> operates correctly. The counter <code>k</code> reacts to changes in the array. That means it wouldn't detect the last number in the array, since there is actually no change until the end. It <em>does</em>, however, detect a change, but <em>accidentally</em> because of the comparison with the element <em>after</em> the array.</p>\n\n<p>You could account for the last number by manually incrementing k at the end. Or you can account manually for the first number in the array:</p>\n\n<pre><code>int PopulateArrayByFrequencyAndReturnLength(int numbers[], int sortedByFrequency[])\n{\n int k = 1;\n sortedByFrequency[0] = numbers[0];\n for(int i = 1; i < 10; i++)\n {\n if(numbers[i-1] != numbers[i])\n {\n sortedByFrequency[k++] = numbers[i];\n }\n }\n return k;\n}\n</code></pre>\n\n<p><strong>Reducing Iterations</strong> </p>\n\n<p><em>1. <code>CalculateFrequency</code></em><br>\nThe function <code>CalculateFrequency</code> runs in <code>O(N^2)</code> but can be done in linear time. If you notice, the number in the array is used as index into the frequency table - only in a complicated fashion. You can used those numbers directly and need to go through <code>numbers</code> only once:</p>\n\n<pre><code>void CalculateFrequency(int numbers[], int frequency[])\n{\n for(int i = 0; i < 10; i++)\n frequency[numbers[i]]++;\n}\n</code></pre>\n\n<p><em>2. <code>SortByFrequency</code></em><br>\nThat is a bubble sort algorithm. I noticed, that you use <code>i</code> for both the outer and the inner loop. The inner loop falls off the end of the array and in later iterations, the <code>i</code> numbers with lowest frequency are already sorted at the end. It is unnecessary to compare those again and again. That means, the inner loop can stop short by <code>i</code>:</p>\n\n<pre><code>void SortByFrequency(int numbers[], int frequency[])\n{\n int hasSorted = 0;\n int temp = 0;\n do\n {\n hasSorted = 0;\n for(int i = 0; i < 9; i++)\n {\n for(int j = 0; j < 9-i; j++)\n {\n if(frequency[numbers[j]] < frequency[numbers[j+1]])\n {\n temp = numbers[j+1];\n numbers[j+1] = numbers[j];\n numbers[j] = temp;\n hasSorted = 1;\n }\n }\n }\n } while (hasSorted);\n}\n</code></pre>\n\n<p><strong>Miscellaneous</strong> </p>\n\n<ul>\n<li>As is, your algorithm doesn't scale well to large arrays with only few different numbers. And using the numbers as index into a frequency table will cause problems if the numbers themselves are very large. But optimisation here depends on the data that is to be expected.</li>\n<li>The length of the array, hard coded inside your functions, should really be an additional parameter.</li>\n<li>Array initialisation can be done shorter:</li>\n</ul>\n\n<p>This sets all entries to zero:</p>\n\n<pre><code>int frequency[10] = {0};\nint sortedByFrequency[10] = {0};\n</code></pre>\n\n<p>Or you could opt to use static arrays, they are initialised to zero:</p>\n\n<pre><code>static int frequency[10];\nstatic int sortedByFrequency[10];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T00:49:04.380",
"Id": "409418",
"Score": "0",
"body": "Nice review from a new contributor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T10:10:04.467",
"Id": "409473",
"Score": "0",
"body": "Thank you for the review, very helpful! Those variables were left over when I refactored the code, I must of forgot to delete them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T20:51:53.213",
"Id": "211721",
"ParentId": "211702",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "211721",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:16:57.197",
"Id": "211702",
"Score": "4",
"Tags": [
"beginner",
"c",
"array",
"sorting"
],
"Title": "Sorting an array of numbers by descending frequency"
} | 211702 |
<p>I would like to know if this is a good solution. This code works but is it efficient enough as i have seen some solutions with <span class="math-container">\$O(1)\$</span> time complexity.</p>
<pre><code> import java.util.Scanner;
public class RotateArray {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] arr = new int[n];
int[] newarr = new int[2 * n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
System.out.println("original array");
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
}
int x = s.nextInt();
for (int i = 0; i < n; i++) {
if(i + x < n) {
newarr[i+x] = arr[i];
}
else
if (i + x >= n) {
int b = i + x - n;
newarr[b] = arr[i];
}
}
for (int i = 0; i < n; i++) {
System.out.println(newarr[i]);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:28:37.493",
"Id": "409370",
"Score": "0",
"body": "You sure its possible to do it in O(1)? Hard to imagine it being better than be better than O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:33:16.493",
"Id": "409371",
"Score": "0",
"body": "You could use 2 calls to java.lang.System.arraycopy() that would be faster than anything you can write your self."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:42:01.603",
"Id": "409373",
"Score": "3",
"body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Bearing in mind that this post came from SO, please read [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"."
}
] | [
{
"body": "<p>Your <code>newarr</code> doesn't need to be twice the size of <code>arr</code>, since you're already checking if <code>i+x<n</code>.</p>\n\n<hr>\n\n<p>Also,</p>\n\n<pre><code>else\n if (i + x >= n) {\n</code></pre>\n\n<p>could just be replaced with <code>else</code>, since the previous condition is <code>if(i + x < n)</code> and it already takes care of the only other possible case.</p>\n\n<hr>\n\n<p>Now that I think about it, you don't need that whole if/else structure. If you're trying to keep the result smaller than n, modulus will do that for you. <code>if (i+x >= n) { b = i+x-n }</code> could just be replaced with the modulus operator - <code>b = (i+x) % n</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:59:12.920",
"Id": "211708",
"ParentId": "211705",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code> for (int i = 0; i < n; i++) {\n if(i + x < n) {\n newarr[i+x] = arr[i];\n }\n else\n if (i + x >= n) {\n int b = i + x - n;\n newarr[b] = arr[i];\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This seems rather complicated. Consider </p>\n\n<pre><code> int rotationPoint = n - x;\n for (int i = 0; i < x; i++) {\n rotated[i] = original[rotationPoint + i];\n }\n\n for (int i = x; i < n; i++) {\n rotated[i] = original[i - x];\n }\n</code></pre>\n\n<p>This has fewer lines of code and no <code>if</code>/<code>else</code> structure. It does use two loops instead of one, but it's still shorter. Both loops are also simpler than the original. And they make it clearer that you are doing one thing and then a different thing, not one of two things on any iteration. </p>\n\n<p>I changed the names of the arrays to ones that made more sense to me. </p>\n\n<p>We can actually get this shorter. </p>\n\n<pre><code> System.arraycopy(original, n - x, rotated, 0, x);\n System.arraycopy(original, 0, rotated, x, n - x);\n</code></pre>\n\n<p>Now, rather than two loops, we have just two lines of code. </p>\n\n<p>This is still going to be <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, but it's going to be one of the more efficient linear time implementations. Copying the array is itself a linear time operation, so you won't be able to do better than that so long as you copy the array. </p>\n\n<p>It is possible to rotate without copying. Basically you build a facade over top the array. Something like </p>\n\n<pre><code>class RotatedArray<T> implements Iterable<T> {\n\n private final T[] original;\n\n private final int rotation;\n\n public RotatedArray<T>(T[] original, int rotation) {\n this.original = original;\n this.rotation = rotation;\n }\n\n private int calculateRotatedIndex(int index) {\n index += rotation;\n if (index >= original.length) {\n index -= original.length;\n }\n\n return index;\n }\n\n public T get(int index) {\n return original[calculateRotatedIndex(index)];\n }\n\n public void set(int index, T datum) {\n original[calculateRotatedIndex(index)] = datum;\n }\n\n public Iterator<T> iterator() {\n return new Iterator<T>() {\n\n private int index = 0;\n\n public boolean hasNext() {\n return original.length > index;\n }\n\n public T next() {\n return original[calculatedRotatedIndex(index++)];\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\n \"Cannot remove an element of an array.\");\n }\n\n };\n }\n\n}\n</code></pre>\n\n<p>The <code>Iterator</code> is modified from the one in <a href=\"https://stackoverflow.com/a/14248833/6660678\">this answer</a>. I retained the <code>remove</code> operation, even though it is unnecessary in Java 8 and higher. I modified it to use a generic type and implement the rotation (without testing, so be careful if you try to use it). </p>\n\n<p>I used an <code>if</code> instead of a modulus so that it will handle out of bounds indexes properly. If the array is size ten and the index is thirty, it should throw an exception (and this does). The modulus version would happily change thirty to zero, which is a valid index. </p>\n\n<p>This would be constant time (<span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>), as it doesn't copy the array. It's just a facade over the array. But this would actually be slower in many situations, as it has to calculated the rotated index on every array access (read or write). I.e. this is a case where asymptotic analysis is misleading. The particular problem here is that we are calculating the asymptotic behavior of two different kinds of operations: copying the array and accessing the array. Copying the array is always going to be linear time. But accessing the array is constant time. </p>\n\n<p>In this case, each array access is going to be slower. But asymptotically that doesn't matter. They are a constant amount slower, regardless of input size. So the question is if, given all the operations we want to do on the array, it would be faster to copy the array first. In many situations, it will. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T12:53:02.540",
"Id": "211763",
"ParentId": "211705",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211763",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T16:22:38.390",
"Id": "211705",
"Score": "-1",
"Tags": [
"java"
],
"Title": "Rotating an array"
} | 211705 |
<p>I have written a solution to the <a href="https://dmoj.ca/problem/ccc00j3" rel="nofollow noreferrer">Slot Machines challenge on DM::OJ</a>:</p>
<blockquote>
<p>Martha takes a jar of quarters to the casino with the intention of becoming rich. She plays three machines in turn. Unknown to her, the machines are entirely predictable. Each play costs one quarter. The first machine pays 30 quarters every 35th time it is played; the second machine pays 60 quarters every 100th time it is played; the third pays
9 quarters every 10th time it is played.</p>
<h3>Input Specification</h3>
<p>Your program should take as input the number of quarters in Martha's jar (there will be at least one and fewer than 1000), and the number of times each machine has been played since it last paid.</p>
<h3>Output Specification</h3>
<p>Your program should output the number of times Martha plays until she goes broke.</p>
<h3>Sample Input</h3>
<pre class="lang-none prettyprint-override"><code>48
3
10
4
</code></pre>
<h3>Sample Output</h3>
<pre class="lang-none prettyprint-override"><code>Martha plays 66 times before going broke.
</code></pre>
</blockquote>
<p>I am seeking to make it run in 2 seconds or less. </p>
<pre class="lang-auto prettyprint-override"><code>money = int(input())
m1 = int(input())
m2 = int(input())
m3 = int(input())
turns = 0
while (money != 0):
#machine 1
money -= 1
m1 += 1
if (m1 == 35):
money += 30
m1 = 0
turns += 1
#machine 2
money -= 1
m2 += 1
if (m2 == 100):
money += 60
m2 = 0
turns += 1
#machine 3
money -= 1
m3 += 1
if (m3 == 10):
money += 9
m3 = 0
turns += 1
print ('Martha plays {} times before going broke.'.format(turns))
</code></pre>
| [] | [
{
"body": "<p><strong>Code organisation, separation of concerns and tests</strong></p>\n\n<p>The code is a single monolithic piece of code. It could be a good idea to reorganise things a bit: to make it clearer, to make it easier to test, to make it easier to maintain, etc.</p>\n\n<p>The first major improvement could be write a function with a clear input (money, m1, m2, m3) and a clear output solving the issue we care about: computing the number of turns.\nThe logic handling the input/output is separated from the logic performing the computation - seel also <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Separation_of_concerns</a> .</p>\n\n<p>Then, this function could be used with inputs from the user but we could also feed it hardcoded values. This can be used to write tests to ensure that the function behaves properly (at least on the example provided by dmoj).</p>\n\n<p>(In the code provided below, I've a simple assert statement to write the tests but it could be a good chance to read about unit test frameworks and start to use them).</p>\n\n<p>Then, you can add any number of tests easily.</p>\n\n<p>Now that we have unit-tests to prevent us from breaking things too badly, we can start tweaking the code.</p>\n\n<p>Finally, you could use <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code></a> to separate the definitions in your code from the code actually using these definitions. It makes your code easier to reuse via the import mechanism.</p>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide called PEP 8</a>. It is followed (more or less stricly) by the Python community. It is highly recommended to read it and try to stick to it when relevant. In your case, you have superfluous parenthesis, indentations of 2 spaces instead of 4, superfluous whitespaces.</p>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def get_number_of_games(money, m1, m2, m3):\n \"\"\"Return the number of games <to be continued>.\"\"\"\n turns = 0\n while money != 0: \n #machine 1\n money -= 1\n m1 += 1\n if m1 == 35: \n money += 30\n m1 = 0\n turns += 1\n\n #machine 2\n money -= 1\n m2 += 1\n if m2 == 100: \n money += 60\n m2 = 0\n turns += 1\n\n #machine 3\n money -= 1\n m3 += 1\n if m3 == 10: \n money += 9\n m3 = 0\n turns += 1\n return turns\n\ndef interactive_main():\n money = int(input())\n m1 = int(input())\n m2 = int(input())\n m3 = int(input())\n print('Martha plays {} times before going broke.'.format(get_number_of_games(money, m1, m2, m3)))\n\ndef unit_test():\n \"\"\"Run unit-tests.\"\"\"\n assert get_number_of_games(48, 3, 10, 4) == 66\n print(\"OK\")\n\nif __name__ == \"__main__\":\n unit_test()\n</code></pre>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>The code is full of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>, making the logic hard to understand.\nWe could store these values into constant with a meaningful name.</p>\n\n<p>Even better, we could store these into appropriate data structures. For a simple solutions, we could decide to use namedtuples.</p>\n\n<pre><code>from collections import namedtuple\n\nMachine = namedtuple('Machine', ['winning_freq', 'profit'])\n\nMACHINE1 = Machine(35, 30)\nMACHINE2 = Machine(100, 60)\nMACHINE3 = Machine(10, 9)\n\ndef get_number_of_games(money, m1, m2, m3):\n \"\"\"Return the number of games <to be continued>.\"\"\"\n turns = 0\n while money != 0:\n money -= 1\n m1 += 1\n if m1 == MACHINE1.winning_freq:\n money += MACHINE1.profit\n m1 = 0\n turns += 1\n\n #machine 2\n money -= 1\n m2 += 1\n if m2 == MACHINE2.winning_freq:\n money += MACHINE2.profit\n m2 = 0\n turns += 1\n\n #machine 3\n money -= 1\n m3 += 1\n if m3 == MACHINE3.winning_freq:\n money += MACHINE3.profit\n m3 = 0\n turns += 1\n return turns\n</code></pre>\n\n<p><strong>Un-handled situations (also known as bugs)</strong></p>\n\n<p>The code is not very robust. A few situations can lead it astray.</p>\n\n<p>Let's take a simple example: we have 1 quarter and the machines haven't been used. This can be written as:</p>\n\n<pre><code>print(get_number_of_games(1, 0, 0, 0))\n</code></pre>\n\n<p>When we run this, we are stuck into a infinite loop. I'll let you investigate the reason why.</p>\n\n<p>Another example - which could be considered invalid but is definitly worth fixing because of how simple it is: we have a lot of money and the machines have been used a lot. For instance, we have:</p>\n\n<pre><code>print(get_number_of_games(1000, 36, 101, 11))\n</code></pre>\n\n<p>Assuming we fix the previous issue: how many turns do we play ? How many times have we won ?</p>\n\n<p>As we fix behaviors, you can add corresponding unit-tests to be sure you don't fall into the same issue later on.</p>\n\n<p><strong>Going further</strong></p>\n\n<p>The code relies on duplicated logic to handle the different machines. A better solution could be to handle them via the same logic. We could imagine having a list of machines.</p>\n\n<p>Also, we could imagine having the numbers of turns played on a given machine stored along with the other information in a <code>Machine</code> class. Then, the <code>get_number_of_games</code> functions could take as inputs an amount of money and a list of properly defined Machines.</p>\n\n<p><strong>Take-away for Python and non-Python code</strong></p>\n\n<ol>\n<li>Make your code testable</li>\n<li>Make your code tested and correct</li>\n<li>Improve it while keeping properties 1 and 2.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T18:05:19.283",
"Id": "211712",
"ParentId": "211709",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "211712",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:19:44.573",
"Id": "211709",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"simulation"
],
"Title": "DM::OJ Slot Machines challenge in Python 3"
} | 211709 |
<p>One of the dream idea to build typewriting in ReactJS. The code seems to be working, still there are something looks not that great in the code
Looking for better solution (best practice) in the function like <code>animationManager()</code> </p>
<p>Demo: <a href="https://codesandbox.io/s/qk4591q1kw" rel="nofollow noreferrer">https://codesandbox.io/s/qk4591q1kw</a></p>
<p><strong>index.js</strong></p>
<pre><code>import React from "react";
import ReactDOM from "react-dom";
import Typewriter from "./Typewriter";
import "./styles.css";
const words = [
"Twinkle twinkle little star",
"How I wonder what you are.",
"Up above the world so high",
"Like a diamond in the sky"
];
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Typewriter data={words} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code></pre>
<p><strong>Typewriter.js</strong></p>
<pre><code>import React, { Component } from "react";
import PropTypes from "prop-types";
import styled, { keyframes } from "styled-components";
let lastTime = performance.now();
const rotate = keyframes`
0% {
border-right: 2px solid tomato;
}
50% {
border-right: 2px solid transparent;
}
100% {
border-right: 2px solid tomato;
}
`;
const Rotate = styled.span`
color: tomato;
animation: ${rotate} 0.7s linear infinite;
`;
class Typewriter extends Component {
state = {
output: ""
};
index = 0;
rafRef = null;
timeoutRef = null;
static defaultProps = {
typingSpeed: 50,
// it needs to implement in delete function
deletingSpeed: 32,
pauseBeforeRestarting: 200,
pauseBeforeDeleting: 1500,
data: [],
style: {},
className: null
};
componentDidMount() {
this.animationManager();
}
componentWillUnmount() {
// cleanup
if (this.timeoutRef) {
clearTimeout(this.timeoutRef);
}
if (this.rafRef) {
cancelAnimationFrame(this.rafRef);
}
}
animationManager = () => {
this.rafRef = requestAnimationFrame(time => {
const typingData = this.props.data;
this.typeEffect(time, typingData[this.index], () => {
this.timeoutRef = setTimeout(() => {
this.rafRef = requestAnimationFrame(time => {
this.deleteEffect(time, () => {
this.timeoutRef = setTimeout(() => {
this.index =
this.index === typingData.length - 1 ? 0 : this.index + 1;
this.animationManager();
}, this.props.pauseBeforeRestarting);
});
});
}, this.props.pauseBeforeDeleting);
});
});
};
typeEffect = (time, text, callback) => {
if (time - lastTime < this.props.typingSpeed) {
this.rafRef = requestAnimationFrame(time => {
this.typeEffect(time, text, callback);
});
return;
}
lastTime = time;
this.setState({
output: text.substr(0, this.state.output.length + 1)
});
if (this.state.output.length < text.length) {
this.rafRef = requestAnimationFrame(time => {
this.typeEffect(time, text, callback);
});
} else {
return callback();
}
};
deleteEffect = (time, callback) => {
if (time - lastTime < this.props.typingSpeed) {
this.rafRef = requestAnimationFrame(time => {
this.deleteEffect(time, callback);
});
return;
}
lastTime = time;
this.setState({
output: this.state.output.substr(0, this.state.output.length - 1)
});
if (this.state.output.length !== 0) {
this.rafRef = requestAnimationFrame(time => {
this.deleteEffect(time, callback);
});
} else {
return callback();
}
};
render() {
return (
<Rotate className={this.props.className} style={this.props.style}>
{this.state.output}
</Rotate>
);
}
}
Typewriter.propTypes = {
typingSpeed: PropTypes.numnber,
deletingSpeed: PropTypes.numnber,
pauseBeforeRestarting: PropTypes.numnber,
pauseBeforeDeleting: PropTypes.numnber,
data: PropTypes.array,
style: PropTypes.object,
className: PropTypes.string
};
export default Typewriter;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T17:13:45.603",
"Id": "409527",
"Score": "0",
"body": "Is the user supposed to be able to type, or does it just simulate text being typed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-20T20:48:03.303",
"Id": "409723",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ It is just typing animation based on strings in the array"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T08:02:50.697",
"Id": "419956",
"Score": "0",
"body": "I think you can do it with only one `setTimeout` - this will add one letter to the string and then check if there are letters left. If so, call the same `setTimeout` again. I think you have too many intervals and requestanimationframes going on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:31:14.383",
"Id": "420005",
"Score": "0",
"body": "@Kokodoko Could you please help for that ?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:38:54.230",
"Id": "211710",
"Score": "2",
"Tags": [
"javascript",
"css",
"ecmascript-6",
"react.js",
"jsx"
],
"Title": "ReactJS Typewriting animation"
} | 211710 |
<p>In the last couple of days I have been programming a chess move generator in Rust from scratch. While it's intent is to be later used in a fully functional engine, where the speed of the move-generation isn't as important, I have had quite some fun optimizing the move-generator. Now, my engine reaches about 85 million nodes per second when testing it with <a href="https://www.chessprogramming.org/Perft" rel="noreferrer">perft</a>, which is about half the speed popular engines like <a href="https://stockfishchess.org" rel="noreferrer">stockfish</a> reach. Now I can't seem to optimize my engine any further. (The perft implementation is using bulk counting aswell)</p>
<p>Internally the board is represented with <a href="https://www.chessprogramming.org/Bitboards" rel="noreferrer">bitboards</a>.
For Move-Generation, <a href="https://www.chessprogramming.org/Magic_Bitboards" rel="noreferrer">magic bitboards</a> are used for sliding pieces, while there is lookup-tables for knights and kings. The pawn's moves are calculated by bit-shifts. I am following this <a href="https://peterellisjones.com/posts/generating-legal-chess-moves-efficiently/" rel="noreferrer">guide</a> for legal move generation, which leaves me with a method <code>generate_moves(g:&GameState)->(Vec<GameMove>,bool)</code>to generate all moves of a given position and a boolean determining if the position is in check. Most of the methods used in the module <code>magic.rs</code> are only there to generate the magic numbers and the lookup-tables for the lookups, and therefor are only used in the beginning.</p>
<p><strong>main.rs</strong></p>
<pre><code>#[macro_use]
extern crate lazy_static;
extern crate rand;
mod game_state;
mod misc;
mod bitboards;
mod movegen;
use self::game_state::GameState;
use std::time::Instant;
fn main() {
let now = Instant::now();
bitboards::init_all();
println!("Should have initialized everything!");
let new_now = Instant::now();
println!("Initialization Time: {}ms", new_now.duration_since(now).as_secs() * 1000 + new_now.duration_since(now).subsec_millis() as u64);
let now = Instant::now();
let g = GameState::from_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
//let g= GameState::from_fen("r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1");
let nodes = perft_div(&g, 6);
println!("{}", nodes);
//misc::STD_FEN);
let new_now = Instant::now();
let time_passed = new_now.duration_since(now).as_secs() as f64 + new_now.duration_since(now).subsec_millis() as f64 / 1000.0;
println!("Time: {}ms", new_now.duration_since(now).as_secs() * 1000 + new_now.duration_since(now).subsec_millis() as u64);
println!("NPS: {}", nodes as f64 / time_passed);
}
pub fn perft_div(g: &GameState, depth: usize) -> u64 {
let mut count = 0u64;
let (valid_moves, in_check) = movegen::generate_moves(&g);
for mv in valid_moves {
let next_g = movegen::make_move(&g, &mv);
let res = perft(&next_g, depth - 1);
println!("{:?}: {}", mv, res);
count += res;
}
count
}
pub fn perft(g: &GameState, depth: usize) -> u64 {
if depth == 1 {
let (vm, _ic) = movegen::generate_moves(&g);
return vm.len() as u64;
} else {
let mut res = 0;
let (valid_moves, incheck) = movegen::generate_moves(&g);
for mv in valid_moves {
res += perft(&movegen::make_move(&g, &mv), depth - 1);
}
res
}
}
</code></pre>
<p>The game_state file contains the simple structs and a method for parsing a FEN-String.</p>
<p><strong>game_state.rs</strong></p>
<pre><code>use std::fmt::{Formatter, Display, Result, Debug};
#[derive(Clone)]
pub enum GameMoveType {
Quiet,
Capture,
EnPassant,
Castle,
Promotion(PieceType),
}
#[derive(Clone, Debug)]
pub enum PieceType {
King,
Pawn,
Knight,
Bishop,
Rook,
Queen,
}
pub struct GameMove {
pub from: usize,
pub to: usize,
pub move_type: GameMoveType,
pub piece_type: PieceType,
}
impl Debug for GameMove {
fn fmt(&self, formatter: &mut Formatter) -> Result {
let mut res_str: String = String::new();
res_str.push_str(&format!("{}{}{}{}", file_to_string(self.from % 8), self.from / 8 + 1, file_to_string(self.to % 8), self.to / 8 + 1));
match &self.move_type {
GameMoveType::Quiet => { res_str.push_str("") }
_ => {}
};
write!(formatter, "{}", res_str)
}
}
fn file_to_string(file: usize) -> &'static str {
match file {
0 => "a",
1 => "b",
2 => "c",
3 => "d",
4 => "e",
5 => "f",
6 => "g",
7 => "h",
_ => panic!("invalid file")
}
}
pub struct GameState {
// 0 = white
// 1 = black
pub color_to_move: usize,
//Array saving all the bitboards
//Index 1:
// 0 -> Pawns
// 1 -> Knights
// 2 -> Bishops
// 3 -> Rooks
// 4 -> Queens
// 5 -> King
//Index 2:
// 0 -> White
// 1 -> Black
pub pieces: [[u64; 2]; 6],
//Castle flags
pub castle_white_kingside: bool,
pub castle_white_queenside: bool,
pub castle_black_kingside: bool,
pub castle_black_queenside: bool,
//En passant flag
pub en_passant: u64,
//50 move draw counter
pub half_moves: usize,
pub full_moves: usize,
//Move-Gen
//King/Knight lookup
//Sliding by magic
}
impl GameState {
pub fn from_fen(fen: &str) -> GameState {
let vec: Vec<&str> = fen.split(" ").collect();
if vec.len() < 4 {
panic!("Invalid FEN");
}
//Parse through FEN
//Piecess
let pieces: Vec<&str> = vec[0].split("/").collect();
if pieces.len() != 8 {
panic!("Invalid FEN");
}
//Iterate over all 8 ranks
let mut pieces_arr: [[u64; 2]; 6] = [[0u64; 2]; 6];
for rank in 0..8 {
let rank_str = pieces[rank];
let mut file: usize = 0;
let mut rank_str_idx: usize = 0;
while file < 8 {
let idx = (7 - rank) * 8 + file;
let next_char = rank_str.chars().nth(rank_str_idx);
rank_str_idx += 1;
match next_char {
Some(x) => {
match x {
'P' => {
pieces_arr[0][0] |= 1u64 << idx;
file += 1;
}
'p' => {
pieces_arr[0][1] |= 1u64 << idx;
file += 1;
}
'N' => {
pieces_arr[1][0] |= 1u64 << idx;
file += 1;
}
'n' => {
pieces_arr[1][1] |= 1u64 << idx;
file += 1;
}
'B' => {
pieces_arr[2][0] |= 1u64 << idx;
file += 1;
}
'b' => {
pieces_arr[2][1] |= 1u64 << idx;
file += 1;
}
'R' => {
pieces_arr[3][0] |= 1u64 << idx;
file += 1;
}
'r' => {
pieces_arr[3][1] |= 1u64 << idx;
file += 1;
}
'Q' => {
pieces_arr[4][0] |= 1u64 << idx;
file += 1;
}
'q' => {
pieces_arr[4][1] |= 1u64 << idx;
file += 1;
}
'K' => {
pieces_arr[5][0] |= 1u64 << idx;
file += 1;
}
'k' => {
pieces_arr[5][1] |= 1u64 << idx;
file += 1;
}
'1' => {
file += 1;
}
'2' => {
file += 2;
}
'3' => {
file += 3;
}
'4' => {
file += 4;
}
'5' => {
file += 5;
}
'6' => {
file += 6;
}
'7' => {
file += 7;
}
'8' => {
file += 8;
}
_ => {
panic!("Invalid FEN");
}
}
}
None => panic!("Invalid FEN"),
}
}
}
//Side to move
let color_to_move = match vec[1] {
"w" => 0,
"b" => 1,
_ => panic!("Invalid FEN!")
};
//CastlingAbilities
let castle_white_kingside = vec[2].contains("K");
let castle_white_queenside = vec[2].contains("Q");
let castle_black_kingside = vec[2].contains("k");
let castle_black_queenside = vec[2].contains("q");
//En Passant target square //Ignore
let mut en_passant: u64 = 0u64;
if vec[3] != "-" {
let mut idx: usize = 0usize;
let file = vec[3].chars().nth(0);
let rank = vec[3].chars().nth(1);
match file {
Some(x) => {
match x {
'a' | 'A' => {}
'b' | 'B' => {
idx += 1;
}
'c' | 'C' => {
idx += 2;
}
'd' | 'D' => {
idx += 3;
}
'e' | 'E' => {
idx += 4;
}
'f' | 'F' => {
idx += 5;
}
'g' | 'G' => {
idx += 6;
}
'h' | 'H' => {
idx += 7;
}
_ => {
panic!("Invalid FEN!");
}
}
}
None => { panic!("Invalid FEN!"); }
}
match rank {
Some(x) => {
match x {
'1' => {}
'2' => {
idx += 8;
}
'3' => {
idx += 16;
}
'4' => {
idx += 24;
}
'5' => {
idx += 32;
}
'6' => {
idx += 40;
}
'7' => {
idx += 48;
}
'8' => {
idx += 56;
}
_ => {
panic!("Invalid FEN!");
}
}
}
None => {
panic!("Invalid FEN!");
}
}
en_passant = 1u64 << idx;
}
let mut half_moves = 0;
let mut full_moves = 0;
if vec.len() > 4 {
//HalfMoveClock
half_moves = vec[4].parse().unwrap();
full_moves = vec[5].parse().unwrap();
}
GameState {
color_to_move,
pieces: pieces_arr,
castle_white_kingside,
castle_white_queenside,
castle_black_kingside,
castle_black_queenside,
half_moves,
full_moves,
en_passant,
}
}
pub fn standard() -> GameState {
GameState {
color_to_move: 0usize,
pieces: [[0xff00u64, 0xff000000000000u64], [0x42u64, 0x4200000000000000u64], [0x24u64, 0x2400000000000000u64], [0x81u64, 0x8100000000000000u64],
[0x8u64, 0x800000000000000u64], [0x10u64, 0x1000000000000000u64]],
castle_white_kingside: true,
castle_white_queenside: true,
castle_black_kingside: true,
castle_black_queenside: true,
en_passant: 0u64,
half_moves: 0usize,
full_moves: 1usize,
}
}
}
</code></pre>
<p><strong>misc.rs</strong></p>
<pre><code>pub const STD_FEN:&str ="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
</code></pre>
<p><strong>bitboards.rs</strong></p>
<pre><code>use rand::Rng;
static mut ROOK_BITS: [usize; 64] = [
12, 11, 11, 11, 11, 11, 11, 12,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
12, 11, 11, 11, 11, 11, 11, 12
];
static mut BISHOP_BITS: [usize; 64] = [
6, 5, 5, 5, 5, 5, 5, 6,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 5, 5, 5, 5, 5, 5, 6
];
const MAGIC_NUMS_ROOKS: [u64; 64] = [
0x2180028011204008u64, 0x21400190002000c0u64, 0x8480100020000b80u64, 0x80100080061800u64, 0xc100080004030010u64, 0x200084430120001u64, 0x1880110006800200u64, 0x100006200804100u64, 0x4084800280400020u64, 0x8400400050002000u64, 0xd001020010342u64, 0x20040102008040u64, 0x8000802400810800u64, 0x2922002804100a01u64, 0x4109002a0099000cu64, 0x40020000840e0841u64, 0x800848000204011u64, 0x900444000201008u64, 0x5201010020049142u64, 0x80620009c20030u64, 0x45310004080100u64, 0x808002001400u64, 0x1090840002100328u64, 0x8022000184085bu64, 0x401080028020u64, 0x4910400080802000u64, 0x1400403100200100u64, 0x910008080180450u64, 0x200040080800800u64, 0x1052000200100429u64, 0x2004e80c000a1110u64, 0x1423000100005282u64, 0x8088834000800aa0u64, 0x10080c000806000u64, 0x8010200082805002u64, 0x82101003000u64, 0x7040080280800400u64, 0x610c004100401200u64, 0x5700010804001002u64, 0x1000008042000904u64, 0x21049460c0008000u64, 0x410014020004002u64, 0x20100a001410013u64, 0x401000810010020u64, 0x4008012400808008u64, 0x808200440480110u64, 0x1b81040200010100u64, 0x8020040040820003u64, 0x80002108508100u64, 0x10242082b008200u64, 0x801004090200100u64, 0x4003002008100100u64, 0x8180080440080u64, 0x890c0004800a0080u64, 0x104020108102400u64, 0x41111040840200u64, 0x1010201601008042u64, 0x127002440013181u64, 0x102104209220082u64, 0xa011009001242009u64, 0x81000228001085u64, 0x5022001008011c02u64, 0x100821000810804u64, 0x100002280d601u64, ];
const MAGIC_NUMS_BISHOPS: [u64; 64] = [
0x6040422a14086080u64, 0x4084800408020u64, 0x400c080210440010u64, 0x44042080000000u64, 0x2610882002100a00u64, 0x9030080c0080u64, 0xc140841048148004u64, 0x200844c100442u64, 0x40042004042682u64, 0x4200100608410a28u64, 0x802010052a202108u64, 0x800c080601410802u64, 0xc001011040020004u64, 0x488811002902400u64, 0xa008024210106808u64, 0x1004a100e9042004u64, 0x2030002102e20800u64, 0x510a5810210042u64, 0x68010408089830u64, 0x41c800802044200u64, 0x4004080a04000u64, 0x4004080203040a00u64, 0x830642382040u64, 0x8200401101c23040u64, 0x8400248108110u64, 0x4440020289080u64, 0x3008040408004050u64, 0x8004004004010002u64, 0x921004024044016u64, 0x201840802020a00u64, 0x20222c0000414811u64, 0x5802068602404810u64, 0x2791200810a29848u64, 0x2650821000081000u64, 0x415000480322u64, 0x2041401820060200u64, 0x1020200240104u64, 0x10802000c2212u64, 0xe002880a00005200u64, 0x2001062200402100u64, 0x52105044000850u64, 0x204590820800818u64, 0x1201410082a00u64, 0x440004200810800u64, 0x20080100442401u64, 0x200b200214100880u64, 0x2810108100400100u64, 0x8824640052011048u64, 0x4281040114400060u64, 0x988824040208001du64, 0x806081c40c040909u64, 0x20090084110014u64, 0x304006022440118u64, 0x1011400304010004u64, 0xa1020010410a048u64, 0x8110020809002809u64, 0x40010022100c0413u64, 0x2800020125011014u64, 0x46082400u64, 0x60408400840401u64, 0x8001020010021204u64, 0x4c00100812084200u64, 0x20000420440c1098u64, 0x802200c01120060u64, ];
lazy_static! {
pub static ref FILES: [u64;8] = initialize_files();
pub static ref NOT_FILES: [u64;8] = initialize_not_files();
pub static ref RANKS: [u64;8] = initialize_ranks();
pub static ref SQUARES: [u64;64]= initialize_squares();
pub static ref NOT_SQUARES: [u64;64]= initialize_not_squares();
pub static ref MAGICS_ROOKS: Vec<Magic>= init_magics_rooks();
pub static ref MAGICS_BISHOPS:Vec<Magic>= init_magics_bishops();
pub static ref KING_ATTACKS:[u64;64] = init_king_attacks();
pub static ref KNIGHT_ATTACKS:[u64;64] = init_knight_attacks();
pub static ref FILES_LESS_THAN:[u64;8]= init_files_less_than();
pub static ref FILES_GREATER_THAN:[u64;8]= init_files_greater_than();
pub static ref RANKS_LESS_THAN:[u64;8]= init_ranks_less_than();
pub static ref RANKS_GREATER_THAN:[u64;8]= init_ranks_greater_than();
}
pub struct Magic {
pub occupancy_mask: u64,
pub shift: usize,
pub magic_num: u64,
pub lookup_table: Vec<u64>,
}
impl Magic {
pub fn get_attacks(&self, all_pieces_board: u64) -> u64 {
self.lookup_table[(((all_pieces_board & self.occupancy_mask).wrapping_mul(self.magic_num)) >> (64 - self.shift)) as usize]
}
}
pub fn init_all() {
FILES.len();
NOT_FILES.len();
RANKS.len();
SQUARES.len();
NOT_SQUARES.len();
//Override Magics with better magic nums
MAGICS_ROOKS.len();
MAGICS_BISHOPS.len();
KING_ATTACKS.len();
KNIGHT_ATTACKS.len();
FILES_LESS_THAN.len();
FILES_GREATER_THAN.len();
RANKS_LESS_THAN.len();
RANKS_GREATER_THAN.len();
}
//Rook-specific magic
pub fn init_magics_rooks() -> Vec<Magic> {
let mut res: Vec<Magic> = Vec::with_capacity(64);
for square in 0..64 {
let shift;
unsafe {
shift = ROOK_BITS[square];
}
let occupancy_mask = occupancy_mask_rooks(square);
if occupancy_mask.count_ones() as usize != shift {
panic!("Not good!");
}
let mut blockers_by_index: Vec<u64> = Vec::with_capacity(1 << shift);
let mut attack_table: Vec<u64> = Vec::with_capacity(1 << shift);
//Initialize lookup table
for i in 0..(1 << shift) {
//i is index of lookup table
blockers_by_index.push(blockers_to_bitboard(i, shift, occupancy_mask));
attack_table.push(rook_attacks_slow(square, blockers_by_index[i]));
}
let magic_num = MAGIC_NUMS_ROOKS[square];
let mut lookup_table = Vec::with_capacity(1 << shift);
for _i in 0..(1 << shift) {
lookup_table.push(0u64);
}
//Calculate look-up table
for i in 0..(1 << shift) {
let j = transform(blockers_by_index[i], magic_num, shift);
if lookup_table[j] == 0u64 {
lookup_table[j] = attack_table[i];
} else {
panic!("Isn't valid num!")
}
}
res.push(Magic {
occupancy_mask,
shift,
magic_num,
lookup_table,
})
}
println!("Finished Initializing Rook Attacks!");
res
}
pub fn occupancy_mask_rooks(square: usize) -> u64 {
(((RANKS[square / 8] & !(FILES[0] | FILES[7])) | (FILES[square % 8] & !(RANKS[0] | RANKS[7]))) & NOT_SQUARES[square])
}
pub fn rook_attacks_slow(square: usize, blocks: u64) -> u64 {
let mut res = 0u64;
let rank: isize = (square / 8) as isize;
let file: isize = (square % 8) as isize;
let dirs: [(isize, isize); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)];
for dir in dirs.iter() {
let (file_i, rank_i) = dir;
let mut rn = rank + rank_i;
let mut fnn = file + file_i;
while rn >= 0 && rn <= 7 && fnn >= 0 && fnn <= 7 {
res |= 1u64 << (rn * 8 + fnn);
if (blocks & (1u64 << (rn * 8 + fnn))) != 0 {
break;
}
rn += rank_i;
fnn += file_i;
}
}
res
}
//Bishop-specific magic
pub fn init_magics_bishops() -> Vec<Magic> {
let mut res: Vec<Magic> = Vec::with_capacity(64);
for square in 0..64 {
let shift;
unsafe {
shift = BISHOP_BITS[square];
}
let occupancy_mask = occupancy_mask_bishops(square);
if occupancy_mask.count_ones() as usize != shift {
panic!("Not good!");
}
let mut blockers_by_index: Vec<u64> = Vec::with_capacity(1 << shift);
let mut attack_table: Vec<u64> = Vec::with_capacity(1 << shift);
//Initialize lookup table
for i in 0..(1 << shift) {
//i is index of lookup table
blockers_by_index.push(blockers_to_bitboard(i, shift, occupancy_mask));
attack_table.push(bishop_attacks_slow(square, blockers_by_index[i]));
}
let magic_num = MAGIC_NUMS_BISHOPS[square];
let mut lookup_table = Vec::with_capacity(1 << shift);
for _i in 0..(1 << shift) {
lookup_table.push(0u64);
}
//Calculate look-up table
for i in 0..(1 << shift) {
let j = transform(blockers_by_index[i], magic_num, shift);
if lookup_table[j] == 0u64 {
lookup_table[j] = attack_table[i];
} else {
panic!("Isn't valid num!")
}
}
res.push(Magic {
occupancy_mask,
shift,
magic_num,
lookup_table,
})
}
println!("Finished Initializing Bishop Attacks!");
res
}
pub fn occupancy_mask_bishops(square: usize) -> u64 {
let mut res = 0u64;
let rk = (square / 8) as isize;
let fl = (square % 8) as isize;
let dirs: [(isize, isize); 4] = [(1, 1), (-1, -1), (1, -1), (-1, 1)];
for dir in dirs.iter() {
let (file_i, rank_i) = dir;
let mut rn = rk + rank_i;
let mut fnn = fl + file_i;
while rn >= 1 && rn <= 6 && fnn >= 1 && fnn <= 6 {
res |= 1u64 << (rn * 8 + fnn);
rn += rank_i;
fnn += file_i;
}
}
res
}
pub fn bishop_attacks_slow(square: usize, blocks: u64) -> u64 {
let mut res = 0u64;
let rank: isize = (square / 8) as isize;
let file: isize = (square % 8) as isize;
let dirs: [(isize, isize); 4] = [(1, 1), (-1, -1), (1, -1), (-1, 1)];
for dir in dirs.iter() {
let (file_i, rank_i) = dir;
let mut rn = rank + rank_i;
let mut fnn = file + file_i;
while rn >= 0 && rn <= 7 && fnn >= 0 && fnn <= 7 {
res |= 1u64 << (rn * 8 + fnn);
if (blocks & (1u64 << (rn * 8 + fnn))) != 0 {
break;
}
rn += rank_i;
fnn += file_i;
}
}
res
}
//General Magic stuff
pub fn transform(blockers: u64, magic: u64, n_bits: usize) -> usize {
((blockers.wrapping_mul(magic)) >> (64 - n_bits)) as usize
}
pub fn generate_magic(blockers_by_index: &Vec<u64>, attack_table: &Vec<u64>, n_bits: usize, occ_mask: u64) -> u64 {
for _iterations in 0..100000000 {
let random_magic = random_u64_fewbits();
if ((occ_mask.wrapping_mul(random_magic)) & 0xFF00000000000000u64) < 6 {
continue;
}
if is_valid_magic(random_magic, n_bits, blockers_by_index, attack_table) {
return random_magic;
}
}
panic!("No Magic found!");
}
pub fn is_valid_magic(magic: u64, n_bits: usize, blockers_by_index: &Vec<u64>, attack_table: &Vec<u64>) -> bool {
let mut used = Vec::with_capacity(1 << n_bits);
for _i in 0..(1 << n_bits) {
used.push(0u64);
}
for i in 0..(1 << n_bits) {
let j = transform(blockers_by_index[i], magic, n_bits);
if used[j] == 0u64 {
used[j] = attack_table[i];
} else if used[j] != attack_table[i] {
return false;
}
}
return true;
}
pub fn random_u64() -> u64 {
rand::thread_rng().gen::<u64>()
}
pub fn random_u64_fewbits() -> u64 {
random_u64() & random_u64() & random_u64()
}
pub fn blockers_to_bitboard(block_index: usize, n_bits: usize, mut mask: u64) -> u64 {
let mut res = 0u64;
for i in 0..n_bits {
let j = mask.trailing_zeros();
mask &= !(1 << j);
if (block_index & (1 << i)) != 0 {
res |= 1u64 << j;
}
}
res
}
//Initializing General BitBoards
pub fn initialize_files() -> [u64; 8] {
let mut res = [0u64; 8];
for file in 0..8 {
if file == 0 {
res[0] = 1u64 << 0 | 1u64 << 8 | 1u64 << 16 | 1u64 << 24 | 1u64 << 32 | 1u64 << 40 | 1u64 << 48 | 1u64 << 56;
} else {
res[file] = res[file - 1] << 1;
}
}
println!("Finished Initializing Files!");
res
}
pub fn initialize_not_files() -> [u64; 8] {
let mut res = [0u64; 8];
for file in 0..8 {
res[file] = !FILES[file];
}
println!("Finished Initializing NOT Files!");
res
}
pub fn initialize_ranks() -> [u64; 8] {
let mut res = [0u64; 8];
for rank in 0..8 {
if rank == 0 {
res[0] = 1u64 << 0 | 1u64 << 1 | 1u64 << 2 | 1u64 << 3 | 1u64 << 4 | 1u64 << 5 | 1u64 << 6 | 1u64 << 7;
} else {
res[rank] = res[rank - 1] << 8;
}
}
println!("Finished Initializing Ranks!");
res
}
pub fn initialize_squares() -> [u64; 64] {
let mut res = [0u64; 64];
for squares in 0..64 {
res[squares] = 1u64 << squares;
}
println!("Finished Initializing Squares!");
res
}
pub fn initialize_not_squares() -> [u64; 64] {
let mut res = [0u64; 64];
for squares in 0..64 {
res[squares] = !(1u64 << squares);
}
println!("Finished Initializing NOT_Squares!");
res
}
pub fn north_one(board: u64) -> u64 {
board << 8
}
pub fn north_east_one(board: u64) -> u64 {
(board & NOT_FILES[7]) << 9
}
pub fn north_west_one(board: u64) -> u64 {
(board & NOT_FILES[0]) << 7
}
pub fn south_one(board: u64) -> u64 {
board >> 8
}
pub fn south_east_one(board: u64) -> u64 {
(board & NOT_FILES[7]) >> 7
}
pub fn south_west_one(board: u64) -> u64 {
(board & NOT_FILES[0]) >> 9
}
pub fn west_one(board: u64) -> u64 {
(board & NOT_FILES[0]) >> 1
}
pub fn east_one(board: u64) -> u64 {
(board & NOT_FILES[7]) << 1
}
pub fn king_attack(mut king_board: u64) -> u64 {
let mut attacks = east_one(king_board) | west_one(king_board);
king_board |= attacks;
attacks |= south_one(king_board) | north_one(king_board);
attacks
}
pub fn init_king_attacks() -> [u64; 64] {
let mut res = [0u64; 64];
for square in 0..64 {
res[square] = king_attack(1u64 << square);
}
println!("Finished Initializing King Attacks!");
res
}
pub fn knight_attack(knight: u64) -> u64 {
let mut attacks;
let mut east = east_one(knight);
let mut west = west_one(knight);
attacks = (east | west) << 16;
attacks |= (east | west) >> 16;
east = east_one(east);
west = west_one(west);
attacks |= (east | west) << 8;
attacks |= (east | west) >> 8;
attacks
}
pub fn init_knight_attacks() -> [u64; 64] {
let mut res = [0u64; 64];
for square in 0..64 {
res[square] = knight_attack(1u64 << square);
}
println!("Finished Initializing Knight Attacks!");
res
}
pub fn init_files_less_than() -> [u64; 8] {
let mut res = [0u64; 8];
for files in 0..8 {
for files_less_than in 0..files {
res[files] |= FILES[files_less_than];
}
}
println!("Finished Initializing FilesLessThan!");
res
}
pub fn init_ranks_less_than() -> [u64; 8] {
let mut res = [0u64; 8];
for ranks in 0..8 {
for ranks_less_than in 0..ranks {
res[ranks] |= RANKS[ranks_less_than];
}
}
println!("Finished Initializing RanksLessThan!");
res
}
pub fn init_files_greater_than() -> [u64; 8] {
let mut res = [0u64; 8];
for files in 0..8 {
res[files] = !FILES_LESS_THAN[files] & !FILES[files];
}
println!("Finished Initializing FilesGreaterThan!");
res
}
pub fn init_ranks_greater_than() -> [u64; 8] {
let mut res = [0u64; 8];
for ranks in 0..8 {
res[ranks] = !RANKS_LESS_THAN[ranks] & !RANKS[ranks];
}
println!("Finished Initializing FilesGreaterThan!");
res
}
//Misc
pub fn to_string_board(board: u64) -> String {
let mut res_str: String = String::new();
res_str.push_str("+---+---+---+---+---+---+---+---+\n");
for rank in 0..8 {
res_str.push_str("| ");
for file in 0..8 {
let idx = 8 * (7 - rank) + file;
if ((board >> idx) & 1) != 0 {
res_str.push_str("X");
} else {
res_str.push_str(" ");
}
res_str.push_str(" | ");
}
res_str.push_str("\n+---+---+---+---+---+---+---+---+\n");
}
res_str
}
</code></pre>
<p>Now in this file all of the moves are calculated.</p>
<hr>
<p><em>King moves</em></p>
<p>This is done by first calculating which of the fields are attacked by pseudo-legal enemy moves. Then the king moves are all of the possible neighbor fields which aren't attacked. If the kings field coincides with one of the attacked fields, we know that the king is in check. If in check, we figure out how many attackers there are and where they are. If it's a double check, only king moves are possible so those are returned. If it's a single check, a capture and a push mask is calculated. Every capture of any piece has to be on this mask, and every non-capture(push) has to land on the push mask.</p>
<hr>
<p><em>Pinned pieces</em></p>
<p>Pinned pieces are determined by simulating a queen on the king's fields which xrays exactly one piece. If her ray lands on an enemy slider, we know that the xray-piece is pinned. The pinned piece may be able to capture the slider or push in the ray of the slider, if it's on the push and capture mask.</p>
<hr>
<p><em>Castles</em></p>
<p>Castles are only possible when not in check. If not in check, we check the castle flags and check the other conditions needed for a castle.</p>
<hr>
<p><em>EnPassants</em></p>
<p>There is a dedicated flag being set on a double push of a pawn. This way we can check any en-passant move.</p>
<hr>
<p><em>Rest of the moves</em></p>
<p>The rest of the moves get generated by lookup and are pseudo-legal. If they land on the push/capture mask, they are legal and get added.</p>
<p><strong>movegen.rs</strong></p>
<pre><code>use super::bitboards;
use super::game_state::{self, GameMove, GameMoveType, PieceType};
//Move GEn
//King- Piece-Wise by lookup
//Knight-Piece-Wise by lookup
//Bishop/Queen/Rook - Piece-Wise by lookup in Magic
//Pawn-SetWise by shift
pub fn king_attack(square: usize) -> u64 {
bitboards::KING_ATTACKS[square]
}
pub fn bishop_attack(square: usize, all_pieces: u64) -> u64 {
bitboards::Magic::get_attacks(&bitboards::MAGICS_BISHOPS[square], all_pieces)
}
pub fn rook_attack(square: usize, all_pieces: u64) -> u64 {
bitboards::Magic::get_attacks(&bitboards::MAGICS_ROOKS[square], all_pieces)
}
pub fn knight_attack(square: usize) -> u64 {
bitboards::KNIGHT_ATTACKS[square]
}
pub fn w_single_push_pawn_targets(pawns: u64, empty: u64) -> u64 {
bitboards::north_one(pawns) & empty
}
pub fn w_double_push_pawn_targets(pawns: u64, empty: u64) -> u64 {
bitboards::north_one(bitboards::north_one(pawns & bitboards::RANKS[1]) & empty) & empty
}
pub fn b_single_push_pawn_targets(pawns: u64, empty: u64) -> u64 {
bitboards::south_one(pawns) & empty
}
pub fn b_double_push_pawn_targets(pawns: u64, empty: u64) -> u64 {
bitboards::south_one(bitboards::south_one(pawns & bitboards::RANKS[6]) & empty) & empty
}
//NorthEast = +9
pub fn w_pawn_east_targets(pawns: u64) -> u64 {
bitboards::north_east_one(pawns)
}
//NorthWest = +7
pub fn w_pawn_west_targets(pawns: u64) -> u64 {
bitboards::north_west_one(pawns)
}
//SouthEast = -7
pub fn b_pawn_east_targets(pawns: u64) -> u64 {
bitboards::south_west_one(pawns)
}
//NorthWest = -9
pub fn b_pawn_west_targets(pawns: u64) -> u64 {
bitboards::south_east_one(pawns)
}
pub fn add_moves(move_list: &mut Vec<GameMove>, from: usize, mut to_board: u64, piece_type: &PieceType, move_type: GameMoveType) {
while to_board != 0u64 {
let idx = to_board.trailing_zeros() as usize;
let move_t_cl = move_type.clone();
let pt_cl= piece_type.clone();
move_list.push(GameMove {
from,
to: idx,
move_type: move_t_cl,
piece_type: pt_cl
});
to_board ^= 1u64 << idx;
//to_board&= to_board-1;
}
}
pub fn add_quiet_pawn_single_pushes(mut single_push_board: u64, color_to_move: &usize, move_list: &mut Vec<GameMove>) {
while single_push_board != 0u64 {
let idx = single_push_board.trailing_zeros() as usize;
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - 8 } else { idx + 8 },
to: idx,
move_type: GameMoveType::Quiet,
piece_type: PieceType::Pawn,
});
single_push_board ^= 1 << idx;
}
}
pub fn add_quiet_pawn_double_pushes(mut double_push_board: u64, color_to_move: &usize, move_list: &mut Vec<GameMove>) {
while double_push_board != 0u64 {
let idx = double_push_board.trailing_zeros() as usize;
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - 16 } else { idx + 16 },
to: idx,
move_type: GameMoveType::Quiet,
piece_type: PieceType::Pawn,
});
double_push_board ^= 1 << idx;
}
}
pub fn add_promotion_push(mut promotion_board: u64, color_to_move: &usize, move_list: &mut Vec<GameMove>, source_shift: usize) {
while promotion_board != 0u64 {
let idx = promotion_board.trailing_zeros() as usize;
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - source_shift } else { idx + source_shift },
to: idx,
move_type: GameMoveType::Promotion(PieceType::Queen),
piece_type: PieceType::Pawn,
});
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - source_shift } else { idx + source_shift },
to: idx,
move_type: GameMoveType::Promotion(PieceType::Rook),
piece_type: PieceType::Pawn,
});
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - source_shift } else { idx + source_shift },
to: idx,
move_type: GameMoveType::Promotion(PieceType::Bishop),
piece_type: PieceType::Pawn,
});
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - source_shift } else { idx + source_shift },
to: idx,
move_type: GameMoveType::Promotion(PieceType::Knight),
piece_type: PieceType::Pawn,
});
promotion_board ^= 1 << idx;
}
}
pub fn add_pawn_capture(mut capture_board: u64, color_to_move: &usize, move_list: &mut Vec<GameMove>, source_shift: usize) {
while capture_board != 0u64 {
let idx = capture_board.trailing_zeros() as usize;
move_list.push(GameMove {
from: if *color_to_move == 0 { idx - source_shift } else { idx + source_shift },
to: idx,
move_type: GameMoveType::Capture,
piece_type: PieceType::Pawn,
});
capture_board ^= 1 << idx;
}
}
pub fn add_en_passants(mut enpassant_board: u64, color_to_move: &usize, move_list: &mut Vec<GameMove>, source_shift: usize, all_pieces_without_my_king: u64, enemy_rooks: u64, my_king_idx: usize) {
while enpassant_board != 0u64 {
let index = enpassant_board.trailing_zeros() as usize;
enpassant_board ^= 1u64 << index;
//Check if rare case didn't happen
//Remove t-7,t-8 or t+7,t+8
let all_pieces_without_en_passants = all_pieces_without_my_king & !bitboards::SQUARES[if *color_to_move == 0 { index - source_shift } else { index + source_shift }]
& !bitboards::SQUARES[if *color_to_move == 0 { index - 8 } else { index + 8 }];
if rook_attack(my_king_idx, all_pieces_without_en_passants) & (!bitboards::FILES[my_king_idx % 8]) & enemy_rooks != 0 {
continue;
}
move_list.push(GameMove {
from: if *color_to_move == 0 { index - source_shift } else { index + source_shift },
to: index,
move_type: GameMoveType::EnPassant,
piece_type: PieceType::Pawn,
});
}
}
//Make moves
pub fn make_move(g: &game_state::GameState, mv: &game_state::GameMove) -> game_state::GameState {
match mv.move_type {
GameMoveType::Quiet => make_quiet_move(&g, &mv),
GameMoveType::Capture => make_capture_move(&g, &mv),
GameMoveType::EnPassant => make_enpassant_move(&g, &mv),
GameMoveType::Castle => make_castle_move(&g, &mv),
GameMoveType::Promotion(PieceType::Queen) | GameMoveType::Promotion(PieceType::Rook) | GameMoveType::Promotion(PieceType::Bishop) | GameMoveType::Promotion(PieceType::Knight)
=> make_promotion_move(&g, &mv),
_ => panic!("Invalid move type")
}
}
pub fn move_piece(pieces: &mut [[u64; 2]; 6], mv: &game_state::GameMove, move_color: usize) {
let index = match mv.piece_type {
PieceType::Pawn => 0,
PieceType::Knight => 1,
PieceType::Bishop => 2,
PieceType::Rook => 3,
PieceType::Queen => 4,
PieceType::King => 5,
};
pieces[index][move_color] ^= bitboards::SQUARES[mv.from];
pieces[index][move_color] |= bitboards::SQUARES[mv.to];
//pieces[index][move_color] ^= 1u64<<mv.from;
//pieces[index][move_color] |= 1u64<<mv.to;
}
pub fn delete_piece(pieces: &mut [[u64; 2]; 6], delete_square: usize, delete_color: usize) {
pieces[0][delete_color] &= bitboards::NOT_SQUARES[delete_square];
pieces[1][delete_color] &= bitboards::NOT_SQUARES[delete_square];
pieces[2][delete_color] &= bitboards::NOT_SQUARES[delete_square];
pieces[3][delete_color] &= bitboards::NOT_SQUARES[delete_square];
pieces[4][delete_color] &= bitboards::NOT_SQUARES[delete_square];
}
pub fn check_castle_flags(ck: bool, cq: bool, mv: &game_state::GameMove, color_to_move: usize, pieces: [[u64; 2]; 6]) -> (bool, bool) {
match mv.piece_type {
PieceType::King => (false, false),
PieceType::Rook => {
let mut new_ck = ck;
if ck {
if color_to_move == 0 {
if pieces[3][0] & bitboards::SQUARES[7] == 0 {
new_ck = false;
}
} else {
if pieces[3][1] & bitboards::SQUARES[63] == 0 {
new_ck = false;
}
}
}
let mut new_cq = cq;
if cq {
if color_to_move == 0 {
if pieces[3][0] & bitboards::SQUARES[0] == 0 {
new_cq = false;
}
} else {
if pieces[3][1] & bitboards::SQUARES[56] == 0 {
new_cq = false;
}
}
}
(new_ck, new_cq)
}
_ => (ck, cq)
}
}
pub fn make_quiet_move(g: &game_state::GameState, mv: &game_state::GameMove) -> game_state::GameState {
let color_to_move = 1 - g.color_to_move;
let mut pieces = g.pieces.clone();
//Make the move
move_piece(&mut pieces, &mv, g.color_to_move);
//Check new castle rights
//The enemies castle right's can't change on a quiet move
let (castle_white_kingside, castle_white_queenside) = if g.color_to_move == 0 {
check_castle_flags(g.castle_white_kingside, g.castle_white_queenside, &mv, g.color_to_move, pieces)
} else { (g.castle_white_kingside, g.castle_white_queenside) };
let (castle_black_kingside, castle_black_queenside) = if g.color_to_move == 0 {
(g.castle_black_kingside, g.castle_black_queenside)
} else { check_castle_flags(g.castle_black_kingside, g.castle_black_queenside, &mv, g.color_to_move, pieces) };
//This will be taken care of later
let mut en_passant = 0u64;
let mut half_moves = g.half_moves + 1;
//Reset half moves if its a pawn move and also check if its a double pawn move, if so, set en passant flag
match mv.piece_type {
PieceType::Pawn => {
half_moves = 0;
if g.color_to_move == 0 && mv.to - mv.from == 16 {
en_passant = bitboards::SQUARES[mv.to - 8];
} else if g.color_to_move == 1 && mv.from - mv.to == 16 {
en_passant = bitboards::SQUARES[mv.to + 8];
}
}
_ => {}
};
//If black was to move, increase full moves by one
let full_moves = g.full_moves + g.color_to_move;
//Create new game state object
game_state::GameState {
color_to_move,
pieces,
castle_white_kingside,
castle_white_queenside,
castle_black_kingside,
castle_black_queenside,
en_passant,
half_moves,
full_moves,
}
}
pub fn make_capture_move(g: &game_state::GameState, mv: &game_state::GameMove) -> game_state::GameState {
let color_to_move = 1 - g.color_to_move;
let mut pieces = g.pieces.clone();
//Make the move
move_piece(&mut pieces, &mv, g.color_to_move);
//Delete to from enemy pieces
delete_piece(&mut pieces, mv.to, color_to_move);
let (mut castle_white_kingside, mut castle_white_queenside) = if g.color_to_move == 0 {
check_castle_flags(g.castle_white_kingside, g.castle_white_queenside, &mv, g.color_to_move, pieces)
} else { (g.castle_white_kingside, g.castle_white_queenside) };
let (mut castle_black_kingside, mut castle_black_queenside) = if g.color_to_move == 0 {
(g.castle_black_kingside, g.castle_black_queenside)
} else { check_castle_flags(g.castle_black_kingside, g.castle_black_queenside, &mv, g.color_to_move, pieces) };
if g.color_to_move == 0 {
//Check that blacks rook didn't get captured
if pieces[3][1] & bitboards::SQUARES[56] == 0 {
castle_black_queenside = false;
}
if pieces[3][1] & bitboards::SQUARES[63] == 0 {
castle_black_kingside = false;
}
} else {
if pieces[3][0] & bitboards::SQUARES[0] == 0 {
castle_white_queenside = false;
}
if pieces[3][0] & bitboards::SQUARES[7] == 0 {
castle_white_kingside = false;
}
}
let en_passant = 0u64;
let half_moves = 0usize;
let full_moves = g.full_moves + g.color_to_move;
game_state::GameState {
color_to_move,
pieces,
castle_white_kingside,
castle_white_queenside,
castle_black_kingside,
castle_black_queenside,
en_passant,
half_moves,
full_moves,
}
}
pub fn make_enpassant_move(g: &game_state::GameState, mv: &game_state::GameMove) -> game_state::GameState {
let color_to_move = 1 - g.color_to_move;
let mut pieces = g.pieces.clone();
//Make the move
move_piece(&mut pieces, &mv, g.color_to_move);
//Delete enemy pawn
delete_piece(&mut pieces, if g.color_to_move == 0 { mv.to - 8 } else { mv.to + 8 }, color_to_move);
let castle_white_kingside = g.castle_white_kingside;
let castle_white_queenside = g.castle_white_queenside;
let castle_black_kingside = g.castle_black_kingside;
let castle_black_queenside = g.castle_black_queenside;
let en_passant = 0u64;
let half_moves = 0usize;
let full_moves = g.full_moves + g.color_to_move;
game_state::GameState {
color_to_move,
pieces,
castle_white_kingside,
castle_white_queenside,
castle_black_kingside,
castle_black_queenside,
en_passant,
half_moves,
full_moves,
}
}
pub fn make_castle_move(g: &game_state::GameState, mv: &game_state::GameMove) -> game_state::GameState {
let color_to_move = 1 - g.color_to_move;
let mut pieces = g.pieces.clone();
//Move the king
move_piece(&mut pieces, &mv, g.color_to_move);
//Move the rook
//Determine if its kingside or queenside castle
//Kingside
if mv.to == 58 {
pieces[3][1] ^= bitboards::SQUARES[56];
pieces[3][1] |= bitboards::SQUARES[59];
} else if mv.to == 2 {
pieces[3][0] ^= bitboards::SQUARES[0];
pieces[3][0] |= bitboards::SQUARES[3];
} else if mv.to == 62 {//Queenside
pieces[3][1] ^= bitboards::SQUARES[63];
pieces[3][1] |= bitboards::SQUARES[61];
} else if mv.to == 6 {
pieces[3][0] ^= bitboards::SQUARES[7];
pieces[3][0] |= bitboards::SQUARES[5];
}
let (castle_white_kingside, castle_white_queenside) = if g.color_to_move == 0 { (false, false) } else {
(g.castle_white_kingside, g.castle_white_queenside)
};
let (castle_black_kingside, castle_black_queenside) = if g.color_to_move == 1 { (false, false) } else {
(g.castle_black_kingside, g.castle_black_queenside)
};
let en_passant = 0u64;
let half_moves = g.half_moves + 1;
let full_moves = g.full_moves + g.color_to_move;
game_state::GameState {
color_to_move,
pieces,
castle_white_kingside,
castle_white_queenside,
castle_black_kingside,
castle_black_queenside,
en_passant,
half_moves,
full_moves,
}
}
pub fn make_promotion_move(g: &game_state::GameState, mv: &game_state::GameMove) -> game_state::GameState {
let color_to_move = 1 - g.color_to_move;
let mut pieces = g.pieces.clone();
//Make the move
move_piece(&mut pieces, &mv, g.color_to_move);
//Delete enemy piece if any on there
delete_piece(&mut pieces, mv.to, color_to_move);
//Delete my pawn
pieces[0][g.color_to_move] ^= bitboards::SQUARES[mv.to];
//Add piece respectivly
pieces[match mv.move_type {
GameMoveType::Promotion(PieceType::Queen) => { 4 }
GameMoveType::Promotion(PieceType::Knight) => { 1 }
GameMoveType::Promotion(PieceType::Bishop) => { 2 }
GameMoveType::Promotion(PieceType::Rook) => { 3 }
_ => panic!("Invalid Type")
}][g.color_to_move] |= bitboards::SQUARES[mv.to];
let mut castle_white_kingside = g.castle_white_kingside;
let mut castle_white_queenside = g.castle_white_queenside;
let mut castle_black_kingside = g.castle_black_kingside;
let mut castle_black_queenside = g.castle_black_queenside;
if g.color_to_move == 0 {
//Check that blacks rook didn't get captured
if pieces[3][1] & bitboards::SQUARES[56] == 0 {
castle_black_queenside = false;
}
if pieces[3][1] & bitboards::SQUARES[63] == 0 {
castle_black_kingside = false;
}
} else {
if pieces[3][0] & bitboards::SQUARES[0] == 0 {
castle_white_queenside = false;
}
if pieces[3][0] & bitboards::SQUARES[7] == 0 {
castle_white_kingside = false;
}
}
let en_passant = 0u64;
let half_moves = 0usize;
let full_moves = g.full_moves + g.color_to_move;
game_state::GameState {
color_to_move,
pieces,
castle_white_kingside,
castle_white_queenside,
castle_black_kingside,
castle_black_queenside,
en_passant,
half_moves,
full_moves,
}
}
pub fn generate_moves(g: &game_state::GameState) -> (Vec<GameMove>, bool) {
//Following this guide:
// https://peterellisjones.com/posts/generating-legal-chess-moves-efficiently/
let mut move_list: Vec<GameMove> = Vec::with_capacity(60);
let color_to_move = g.color_to_move;
let enemy_color = 1 - color_to_move;
//Get my pieces
let my_king = g.pieces[5][color_to_move];
let my_king_idx = my_king.trailing_zeros() as usize;
let mut my_pawns = g.pieces[0][color_to_move];
let mut my_knights = g.pieces[1][color_to_move];
let mut my_bishops = g.pieces[2][color_to_move] | g.pieces[4][color_to_move];
let mut my_rooks = g.pieces[3][color_to_move] | g.pieces[4][color_to_move];
//Need this to xor out queens later, when we look at pinned pieces
let my_queens = g.pieces[4][color_to_move];
//Get enemy pieces
let enemy_king = g.pieces[5][enemy_color];
let enemy_king_idx = enemy_king.trailing_zeros() as usize;
let enemy_pawns = g.pieces[0][enemy_color];
let enemy_knights = g.pieces[1][enemy_color];
let enemy_bishops = g.pieces[2][enemy_color] | g.pieces[4][enemy_color];
let enemy_rooks = g.pieces[3][enemy_color] | g.pieces[4][enemy_color];
let my_pieces = my_king | my_pawns | my_knights | my_bishops | my_rooks;
let not_my_pieces = !my_pieces;
let enemy_sliders = enemy_bishops | enemy_rooks;
let enemy_pieces = enemy_pawns | enemy_knights | enemy_sliders | enemy_king;
let not_enemy_pieces = !enemy_pieces;
let all_pieces_without_my_king = enemy_pieces | (my_pieces & !my_king);
let all_pieces = all_pieces_without_my_king | my_king;
let empty = !all_pieces;
let unsafe_white_squares = if color_to_move == 0 {
get_b_attacked_squares(enemy_king_idx, enemy_pawns, enemy_knights, enemy_bishops, enemy_rooks
, all_pieces_without_my_king)
} else {
get_w_attacked_squares(enemy_king_idx, enemy_pawns, enemy_knights, enemy_bishops, enemy_rooks
, all_pieces_without_my_king)
};
let possible_king_moves = king_attack(my_king_idx) & !unsafe_white_squares & not_my_pieces;
add_moves(&mut move_list, my_king_idx, possible_king_moves & not_enemy_pieces, &PieceType::King, GameMoveType::Quiet);
add_moves(&mut move_list, my_king_idx, possible_king_moves & enemy_pieces, &PieceType::King, GameMoveType::Capture);
let (king_attackers_board, checking_piece_is_slider, checking_piece_slider_is_bishop) = if unsafe_white_squares & my_king == 0 {
(0u64, false, false)
} else {
if color_to_move == 0 {
attackers_from_black(my_king, my_king_idx, enemy_pawns, enemy_knights
, enemy_bishops, enemy_rooks, all_pieces)
} else {
attackers_from_white(my_king, my_king_idx, enemy_pawns, enemy_knights
, enemy_bishops, enemy_rooks, all_pieces)
}
};
let num_checkers = king_attackers_board.count_ones();
//Double check
if num_checkers > 1 { //Then only king moves are possible anyway
return (move_list, true);
}
//Calculate capture and push mask
let mut capture_mask = 0xFFFFFFFFFFFFFFFFu64;
let mut push_mask = 0xFFFFFFFFFFFFFFFFu64;
//Single-Check
{
if num_checkers == 1 {
capture_mask = king_attackers_board;
if checking_piece_is_slider {
let checking_piece_square = king_attackers_board.trailing_zeros() as usize;
if checking_piece_slider_is_bishop {
push_mask = get_bishop_ray(bishop_attack(checking_piece_square, 0u64), my_king_idx, checking_piece_square);
} else {
push_mask = get_rook_ray(rook_attack(checking_piece_square, 0u64), my_king_idx, checking_piece_square);
}
} else {
push_mask = 0u64;
}
}
}
//Pinned pieces
{//Pinned by rook
let rook_attacks_from_my_king_postion = rook_attack(my_king_idx, all_pieces);
//See one layer through my pieces
//If a rook is found seeing through one piece, the piece is pinned
let xray_rooks = xray_rook_attacks(rook_attacks_from_my_king_postion, all_pieces, my_pieces, my_king_idx);
//Go through all directions
//Find the rooks with xray
let mut rooks_on_xray = xray_rooks & enemy_rooks;
while rooks_on_xray != 0 {
let rook_position = rooks_on_xray.trailing_zeros() as usize;
rooks_on_xray &= rooks_on_xray - 1;
let ray = get_rook_ray(rook_attacks_from_my_king_postion | xray_rooks, rook_position, my_king_idx);
let pinned_piece = ray & my_pieces;
let pinned_piece_position = pinned_piece.trailing_zeros() as usize;
if pinned_piece & my_rooks != 0 {
let mut piece_type = PieceType::Rook;
if pinned_piece & my_queens != 0 {
my_bishops ^= pinned_piece;
piece_type = PieceType::Queen;
}
my_rooks ^= pinned_piece;
add_moves(&mut move_list, pinned_piece_position, ray & !pinned_piece & push_mask, &piece_type, GameMoveType::Quiet);
//Don't forget that we can capture the rook aswell
add_moves(&mut move_list, pinned_piece_position, bitboards::SQUARES[rook_position] & capture_mask, &piece_type, GameMoveType::Capture);
continue;
}
if pinned_piece & my_pawns != 0 {
my_pawns ^= pinned_piece;
let pawn_push_once = if color_to_move == 0 { w_single_push_pawn_targets(pinned_piece, empty) } else { b_single_push_pawn_targets(pinned_piece, empty) } & ray;
let pawn_push_twice = if color_to_move == 0 { w_double_push_pawn_targets(pinned_piece, empty) } else { b_double_push_pawn_targets(pinned_piece, empty) } & ray;
add_moves(&mut move_list, pinned_piece_position, (pawn_push_once | pawn_push_twice) & push_mask, &PieceType::Pawn, GameMoveType::Quiet);
continue;
}
if pinned_piece & my_knights != 0 {
my_knights ^= pinned_piece;
continue;
}
if pinned_piece & my_bishops != 0 {
my_bishops ^= pinned_piece;
}
}
//Pinned by bishop
let bishop_attacks_from_my_king_position = bishop_attack(my_king_idx, all_pieces);
let xray_bishops = xray_bishop_attacks(bishop_attacks_from_my_king_position, all_pieces, my_pieces, my_king_idx);
let mut bishops_on_xray = xray_bishops & enemy_bishops;
while bishops_on_xray != 0 {
let bishop_position = bishops_on_xray.trailing_zeros() as usize;
bishops_on_xray &= bishops_on_xray - 1;
let ray = get_bishop_ray(bishop_attacks_from_my_king_position | xray_bishops, bishop_position, my_king_idx);
let pinned_piece = ray & my_pieces;
let pinned_piece_position = pinned_piece.trailing_zeros() as usize;
if pinned_piece & my_bishops != 0 {
let mut piece_type = PieceType::Bishop;
if pinned_piece & my_queens != 0 {
my_rooks ^= pinned_piece;
piece_type = PieceType::Queen;
}
my_bishops ^= pinned_piece;
add_moves(&mut move_list, pinned_piece_position, ray & !pinned_piece & push_mask, &piece_type, GameMoveType::Quiet);
add_moves(&mut move_list, pinned_piece_position, bitboards::SQUARES[bishop_position] & capture_mask, &piece_type, GameMoveType::Capture);
continue;
}
if pinned_piece & my_pawns != 0 {
my_pawns ^= pinned_piece;
let pawn_targets = if color_to_move == 0 { w_pawn_east_targets(pinned_piece) } else { b_pawn_east_targets(pinned_piece) } | if color_to_move == 0 { w_pawn_west_targets(pinned_piece) } else { b_pawn_west_targets(pinned_piece) };
let pawn_captures = pawn_targets & bitboards::SQUARES[bishop_position] & capture_mask;
//let pawn_enpassants = pawn_targets & g.en_passant;
add_moves(&mut move_list, pinned_piece_position, pawn_captures, &PieceType::Pawn, GameMoveType::Capture);
//add_moves(&mut move_list, pinned_piece_position, pawn_enpassants, &PieceType::Pawn, GameMoveType::EnPassant);
continue;
}
if pinned_piece & my_knights != 0 {
my_knights ^= pinned_piece;
continue;
}
if pinned_piece & my_rooks != 0 {
my_rooks ^= pinned_piece;
}
}
}
//Calculate normal moves
//Pawns
{
//Single push
{
let my_pawns_single_push = if color_to_move == 0 { w_single_push_pawn_targets(my_pawns, empty) } else { b_single_push_pawn_targets(my_pawns, empty) } & push_mask;
let my_pawns_no_promotion = my_pawns_single_push & !bitboards::RANKS[if color_to_move == 0 { 7 } else { 0 }];
let my_pawns_promotion = my_pawns_single_push & bitboards::RANKS[if color_to_move == 0 { 7 } else { 0 }];
add_quiet_pawn_single_pushes(my_pawns_no_promotion, &color_to_move, &mut move_list);
add_promotion_push(my_pawns_promotion, &color_to_move, &mut move_list, 8usize);
}
//Double push
{
let my_pawns_double_push = if color_to_move == 0 { w_double_push_pawn_targets(my_pawns, empty) } else { b_double_push_pawn_targets(my_pawns, empty) } & push_mask;
add_quiet_pawn_double_pushes(my_pawns_double_push, &color_to_move, &mut move_list);
}
//Capture west
{
let my_pawns_west_targets = if color_to_move == 0 { w_pawn_west_targets(my_pawns) } else { b_pawn_west_targets(my_pawns) };
let my_pawns_west_normal_captures = my_pawns_west_targets & capture_mask & enemy_pieces;
//Checking for promotion on capture
let my_pawns_no_promotion = my_pawns_west_normal_captures & !bitboards::RANKS[if color_to_move == 0 { 7 } else { 0 }];
let my_pawns_promotion = my_pawns_west_normal_captures & bitboards::RANKS[if color_to_move == 0 { 7 } else { 0 }];
//Capture
add_pawn_capture(my_pawns_no_promotion, &color_to_move, &mut move_list, 7usize);
//Promotion capture
add_promotion_push(my_pawns_promotion, &color_to_move, &mut move_list, 7usize);
//En passant
//We can capture en passant, if its in capture mask aswell
let my_pawns_west_enpassants = my_pawns_west_targets & g.en_passant & if color_to_move == 0 { capture_mask << 8 } else { capture_mask >> 8 };
add_en_passants(my_pawns_west_enpassants, &color_to_move, &mut move_list, 7usize, all_pieces_without_my_king, enemy_rooks, my_king_idx);
}
//Capture east
{
let my_pawns_east_targets = if color_to_move == 0 { w_pawn_east_targets(my_pawns) } else { b_pawn_east_targets(my_pawns) };
let my_pawns_east_normal_captures = my_pawns_east_targets & capture_mask & enemy_pieces;
//Checking for promotion on capture
let my_pawns_no_promotion = my_pawns_east_normal_captures & !bitboards::RANKS[if color_to_move == 0 { 7 } else { 0 }];
let my_pawns_promotion = my_pawns_east_normal_captures & bitboards::RANKS[if color_to_move == 0 { 7 } else { 0 }];
add_pawn_capture(my_pawns_no_promotion, &color_to_move, &mut move_list, 9usize);
add_promotion_push(my_pawns_promotion, &color_to_move, &mut move_list, 9usize);
//En passants
let my_pawns_east_enpassants = my_pawns_east_targets & g.en_passant & if color_to_move == 0 { capture_mask << 8 } else { capture_mask >> 8 };
add_en_passants(my_pawns_east_enpassants, &color_to_move, &mut move_list, 9usize, all_pieces_without_my_king, enemy_rooks, my_king_idx);
}
}
//Knights
{
while my_knights != 0u64 {
let index = if color_to_move == 0 { 63usize - my_knights.leading_zeros() as usize } else { my_knights.trailing_zeros() as usize };
let my_knight_attacks = knight_attack(index) & not_my_pieces;
let my_knight_captures = my_knight_attacks & enemy_pieces & capture_mask;
add_moves(&mut move_list, index, my_knight_captures, &PieceType::Knight, GameMoveType::Capture);
let my_knight_quiets = my_knight_attacks & !enemy_pieces & push_mask;
add_moves(&mut move_list, index, my_knight_quiets, &PieceType::Knight, GameMoveType::Quiet);
my_knights ^= 1u64 << index;
}
}
//Bishops
{
while my_bishops != 0u64 {
let index = if color_to_move == 0 { 63usize - my_bishops.leading_zeros() as usize } else { my_bishops.trailing_zeros() as usize };
let my_bishop_attack = bishop_attack(index, all_pieces) & not_my_pieces;
let my_bishop_capture = my_bishop_attack & enemy_pieces & capture_mask;
let piece_type = if bitboards::SQUARES[index] & my_queens != 0 { PieceType::Queen } else { PieceType::Bishop };
add_moves(&mut move_list, index, my_bishop_capture, &piece_type, GameMoveType::Capture);
let my_bishop_quiet = my_bishop_attack & !enemy_pieces & push_mask;
add_moves(&mut move_list, index, my_bishop_quiet, &piece_type, GameMoveType::Quiet);
my_bishops ^= 1u64 << index;
}
}
//Rooks
{
while my_rooks != 0u64 {
let index = if color_to_move == 0 { 63usize - my_rooks.leading_zeros() as usize } else { my_rooks.trailing_zeros() as usize };
let my_rook_attack = rook_attack(index, all_pieces) & not_my_pieces;
let my_rook_capture = my_rook_attack & enemy_pieces & capture_mask;
let piece_type = if bitboards::SQUARES[index] & my_queens != 0 { PieceType::Queen } else { PieceType::Rook };
add_moves(&mut move_list, index, my_rook_capture, &piece_type, GameMoveType::Capture);
let my_rook_quiets = my_rook_attack & !enemy_pieces & push_mask;
add_moves(&mut move_list, index, my_rook_quiets, &piece_type, GameMoveType::Quiet);
my_rooks ^= 1u64 << index;
}
}
//Castles
if num_checkers == 0 {
if g.color_to_move == 0 {
//Make sure there is no piece in between and safe squares
if g.castle_white_kingside {
if (all_pieces | unsafe_white_squares) & (bitboards::SQUARES[5] | bitboards::SQUARES[6]) == 0 {
move_list.push(GameMove {
from: my_king_idx,
to: 6usize,
move_type: GameMoveType::Castle,
piece_type: PieceType::King,
});
}
}
if g.castle_white_queenside {
if ((all_pieces | unsafe_white_squares) & (bitboards::SQUARES[2] | bitboards::SQUARES[3]) | all_pieces & bitboards::SQUARES[1]) == 0 {
move_list.push(GameMove {
from: my_king_idx,
to: 2usize,
move_type: GameMoveType::Castle,
piece_type: PieceType::King,
});
}
}
} else {
if g.castle_black_kingside {
if (all_pieces | unsafe_white_squares) & (bitboards::SQUARES[61] | bitboards::SQUARES[62]) == 0 {
move_list.push(GameMove {
from: my_king_idx,
to: 62usize,
move_type: GameMoveType::Castle,
piece_type: PieceType::King,
});
}
}
if g.castle_black_queenside {
if ((all_pieces | unsafe_white_squares) & (bitboards::SQUARES[58] | bitboards::SQUARES[59]) | all_pieces & bitboards::SQUARES[57]) == 0 {
move_list.push(GameMove {
from: my_king_idx,
to: 58usize,
move_type: GameMoveType::Castle,
piece_type: PieceType::King,
});
}
}
}
}
(move_list, num_checkers > 0)
}
pub fn xray_rook_attacks(attacks: u64, occupied_square: u64, one_time_blockers: u64, rook_square: usize) -> u64 {
return attacks ^ rook_attack(rook_square, occupied_square ^ (one_time_blockers & attacks));
}
pub fn xray_bishop_attacks(attacks: u64, occupied_square: u64, one_time_blockers: u64, bishop_square: usize) -> u64 {
return attacks ^ bishop_attack(bishop_square, occupied_square ^ (one_time_blockers & attacks));
}
//Gets the ray of one rook into a specific direction
pub fn get_rook_ray(rook_attacks_in_all_directions: u64, target_square: usize, rook_square: usize) -> u64 {
let diff = target_square as isize - rook_square as isize;
let target_rank = target_square / 8;
let target_file = target_square % 8;
let rook_rank = rook_square / 8;
let rook_file = rook_square % 8;
if diff > 0 {
//Same vertical
if target_rank == rook_rank {
return bitboards::FILES_LESS_THAN[target_file] & bitboards::FILES_GREATER_THAN[rook_file] & rook_attacks_in_all_directions;
} else {
return bitboards::RANKS_LESS_THAN[target_rank] & bitboards::RANKS_GREATER_THAN[rook_rank] & rook_attacks_in_all_directions;
}
} else {
if target_rank == rook_rank {
return bitboards::FILES_GREATER_THAN[target_file] & bitboards::FILES_LESS_THAN[rook_file] & rook_attacks_in_all_directions;
} else {
return bitboards::RANKS_GREATER_THAN[target_rank] & bitboards::RANKS_LESS_THAN[rook_rank] & rook_attacks_in_all_directions;
}
}
}
//Gets the rof of one bishop into a specific direction
pub fn get_bishop_ray(bishop_attack_in_all_directions: u64, target_square: usize, bishop_square: usize) -> u64 {
let diff = target_square as isize - bishop_square as isize;
let target_rank = target_square / 8;
let target_file = target_square % 8;
let bishop_rank = bishop_square / 8;
let bishop_file = bishop_square % 8;
if diff > 0 {
if diff % 7 == 0 {
return bitboards::FILES_GREATER_THAN[target_file] & bitboards::FILES_LESS_THAN[bishop_file]
& bitboards::RANKS_LESS_THAN[target_rank] & bitboards::RANKS_GREATER_THAN[bishop_rank]
& bishop_attack_in_all_directions;
} else {
return bitboards::FILES_LESS_THAN[target_file] & bitboards::FILES_GREATER_THAN[bishop_file]
& bitboards::RANKS_LESS_THAN[target_rank] & bitboards::RANKS_GREATER_THAN[bishop_rank]
& bishop_attack_in_all_directions;
}
} else {
if diff % -7 == 0 {
return bitboards::FILES_LESS_THAN[target_file] & bitboards::FILES_GREATER_THAN[bishop_file]
& bitboards::RANKS_GREATER_THAN[target_rank] & bitboards::RANKS_LESS_THAN[bishop_rank]
& bishop_attack_in_all_directions;
} else {
return bitboards::FILES_GREATER_THAN[target_file] & bitboards::FILES_LESS_THAN[bishop_file]
& bitboards::RANKS_GREATER_THAN[target_rank] & bitboards::RANKS_LESS_THAN[bishop_rank]
& bishop_attack_in_all_directions;
}
}
}
pub fn attackers_from_white(square_board: u64, square: usize, white_pawns: u64, white_knights: u64, white_bishops: u64, white_rooks: u64, blockers: u64) -> (u64, bool, bool) {
let mut attackers = 0u64;
let mut slider_flag = false;
let mut bishop_slider = false;
attackers |= knight_attack(square) & white_knights;
attackers |= (b_pawn_west_targets(square_board) | b_pawn_east_targets(square_board)) & white_pawns;
let bishop_attacks = bishop_attack(square, blockers) & white_bishops;
attackers |= bishop_attacks;
if bishop_attacks != 0 {
slider_flag = true;
bishop_slider = true;
}
let rook_attacks = rook_attack(square, blockers) & white_rooks;
attackers |= rook_attacks;
if rook_attacks != 0 {
slider_flag = true;
}
(attackers, slider_flag, bishop_slider)
}
pub fn attackers_from_black(square_board: u64, square: usize, black_pawns: u64, black_knights: u64, black_bishops: u64, black_rooks: u64, blockers: u64) -> (u64, bool, bool) {
let mut attackers = 0u64;
let mut slider_flag = false;
let mut bishop_slider = false;
attackers |= knight_attack(square) & black_knights;
attackers |= (w_pawn_west_targets(square_board) | w_pawn_east_targets(square_board)) & black_pawns;
let bishop_attacks = bishop_attack(square, blockers) & black_bishops;
attackers |= bishop_attacks;
if bishop_attacks != 0 {
slider_flag = true;
bishop_slider = true;
}
let rook_attacks = rook_attack(square, blockers) & black_rooks;
attackers |= rook_attacks;
if rook_attacks != 0 {
slider_flag = true;
}
(attackers, slider_flag, bishop_slider)
}
pub fn get_w_attacked_squares(white_king_idx: usize, white_pawns: u64, mut white_knights: u64, mut white_bishops: u64, mut white_rooks: u64, blocked_squares: u64) -> u64 {
let mut res = 0u64;
res |= king_attack(white_king_idx);
res |= w_pawn_west_targets(white_pawns) | w_pawn_east_targets(white_pawns);
while white_knights != 0u64 {
let sq = 63usize - white_knights.leading_zeros() as usize;
res |= knight_attack(sq);
white_knights ^= 1u64 << sq;
}
while white_bishops != 0u64 {
let sq = 63usize - white_bishops.leading_zeros() as usize;
res |= bishop_attack(sq, blocked_squares);
white_bishops ^= 1u64 << sq;
}
while white_rooks != 0u64 {
let sq = 63usize - white_rooks.leading_zeros() as usize;
res |= rook_attack(sq, blocked_squares);
white_rooks ^= 1u64 << sq;
}
res
}
pub fn get_b_attacked_squares(black_king_idx: usize, black_pawns: u64, mut black_knights: u64, mut black_bishops: u64, mut black_rooks: u64, blocked_squares: u64) -> u64 {
let mut res = 0u64;
res |= king_attack(black_king_idx);
res |= b_pawn_west_targets(black_pawns) | b_pawn_east_targets(black_pawns);
while black_knights != 0u64 {
let sq = black_knights.trailing_zeros() as usize;
res |= knight_attack(sq);
black_knights ^= 1u64 << sq;
}
while black_bishops != 0u64 {
let sq = black_bishops.trailing_zeros() as usize;
res |= bishop_attack(sq, blocked_squares);
black_bishops ^= 1u64 << sq;
}
while black_rooks != 0u64 {
let sq = black_rooks.trailing_zeros() as usize;
res |= rook_attack(sq, blocked_squares);
black_rooks ^= 1u64 << sq;
}
res
}
</code></pre>
<p>A quick look into valgrind/callgrind
<a href="https://i.stack.imgur.com/zUYKh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zUYKh.png" alt="Callgrind result"></a>
also reveals the fact, that <code>add_moves()</code> takes up about 25% of the runtime, while all it does is iterating through the target-squares and pushing the moves found into the <code>move_list</code> vector.This seems a bit odd to me. Weirdly enough, adding <code>#[inline(always)]</code> to all of the add_moves functions increases the generation speed from 75 to 85 million nodes per second.</p>
<p>Now my question is, am I missing a core concept of move generation here, or is my code just badly written? If it's badly written, how can I improve?</p>
<p>I should also mention that I am still pretty new to rust, so I am glad about any non-idiomacy being pointed out.</p>
<p>In the <a href="https://github.com/fabianvdW/ChessInRust/blob/master/src/main.rs#L61" rel="noreferrer">github repository</a> there are also about 50 test cases which indeed confirm that my implementation is working.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T17:50:19.870",
"Id": "211711",
"Score": "4",
"Tags": [
"performance",
"beginner",
"rust",
"chess"
],
"Title": "Move-generation for chess in rust"
} | 211711 |
<p>I would like to plot the following function:</p>
<p><span class="math-container">$$
\begin{align}
\Lambda(\delta\tau) &\equiv\ \chi(\delta\tau, 0)
= \frac{1}{T_i} \int_0^{T_i} a(t_0+t')a(t_0+t'+\delta\tau) dt' \\
&= \begin{cases}
1 - \frac{\left|\delta\tau\right|}{\tau_c}, &\left|\delta\tau\right| \le \tau_c(1+\frac{\tau_c}{T_i}) \\
-\frac{\tau_c}{T_i}, &\left|\delta\tau\right| \gt \tau_c(1+\frac{\tau_c}{T_i}) \\
\end{cases}
\end{align}
$$</span>
which represents a simple triangular shape.
There is a conditional statement. My implementation uses a <code>for</code> loop as follows:</p>
<pre><code>def waf_delay(delay_increment):
for d in delay_increment:
if np.abs(d) <= delay_chip*(1+delay_chip/integration_time):
yield 1 - np.abs(d)/delay_chip
else:
yield -delay_chip/integration_time;
integration_time = 1e-3 # seconds
delay_chip = 1/1.023e6 # seconds
x=np.arange(-5.0, 5.0, 0.1)
y=list(waf_delay(x))
plt.plot(x, y)
plt.show()
</code></pre>
<p>Is there a more correct way to transform an array based on a condition rather than just looping through it? Instead of having something like this:</p>
<blockquote>
<pre><code>def f(x_array):
for x in x_array:
if np.abs(x) <= 3:
yield 1 - x/3
else:
yield 0
x=np.arange(-5.0, 5.0, 0.1)
y=list(f(x))
plt.plot(x, y)
plt.show()
</code></pre>
</blockquote>
<p>I would like to write something like this:</p>
<blockquote>
<pre><code>def f(x):
if np.abs(x) <= 3:
yield 1 - x/3
else:
yield 0
x=np.arange(-5.0, 5.0, 0.1)
plt.plot(x, f(x))
plt.show()
</code></pre>
</blockquote>
<p>that could take an array. </p>
| [] | [
{
"body": "<p>There are two ways to solve this problem. The first one is <a href=\"https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\"><code>numpy.where</code></a>, which can take two arrays and it will choose from one wherever a condition is true and from the other wherever it is false. This only works if your piecewise function has only two possible states (as is the case here):</p>\n\n<pre><code>def waf_delay(delays):\n return np.where(np.abs(delays) <= delay_chip*(1+delay_chip/integration_time),\n 1 - np.abs(delays)/delay_chip,\n -delay_chip/integration_time)\n</code></pre>\n\n<p>Another more general possibility is to use <a href=\"https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.piecewise.html\" rel=\"nofollow noreferrer\"><code>numpy.piecewise</code></a>, but that is probably overkill here:</p>\n\n<pre><code>def f1(x):\n return 1 - np.abs(x)/delay_chip\n\ndef f2(x):\n return -delay_chip/integration_time\n\ncut_off = delay_chip*(1+delay_chip/integration_time)\ny = np.piecewise(x, [np.abs(x) <= cut_off, np.abs(x) > cut_off], [f1, f2])\n</code></pre>\n\n<p>Note that in both cases no <code>for d in delays</code> is needed, because all functions used are vecotorized (the basic arithmetic operations for <code>numpy</code> arrays are and so is <code>numpy.abs</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T18:18:39.917",
"Id": "409532",
"Score": "0",
"body": "Very clean. This is exactly what I was expecting to be possible to do but I wasn't sure how. Do you have any recommendation on where to learn this algorithms?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T20:39:26.767",
"Id": "409542",
"Score": "0",
"body": "@WooWapDaBug Looking at SO questions/answers about numpy and reading the documentation helped me to learn a lot about neat tricks. Also having to use it somewhere obviously helps, but I don't know of any tutorial that gets into the advanced stuff in a good way..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T21:08:26.480",
"Id": "409548",
"Score": "1",
"body": "Graipher Very true. I try my best to learn and to contribute from SO. Thank you very much for sharing your knowledge. It is very valuable"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-18T15:06:08.157",
"Id": "211770",
"ParentId": "211715",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211770",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T18:43:35.043",
"Id": "211715",
"Score": "1",
"Tags": [
"python",
"numpy",
"matplotlib"
],
"Title": "Plot a piecewise-defined function"
} | 211715 |
<p>I have a very simple Python script. All it does is open two data files from a given directory, read the data, make a series of plots and save as PDF. It works, but it is very slow. It takes almost 20 seconds for data files that have 50-100 lines and <30 variables.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
with open('file1.out') as f:
var1 = f.readline().split()
with open('file2.out') as f:
var1 = f.readline().split()
df1 = np.loadtxt('file1.out', skiprows=1, unpack=True)
df2 = np.loadtxt('file2.out', skiprows=1, unpack=True)
nc1 = df1.shape[0]
nc2 = df2.shape[0]
with PdfPages('file_output.pdf') as pdf:
## file1.out
fig = plt.figure(figsize=(11,7))
j = 1
for i in range(1,nc1):
ax = fig.add_subplot(3,2,j)
ax.plot(df1[0], df1[i], linestyle='-', color='black')
ax.set(title=var1[i], xlabel='seconds', ylabel='')
if j == 6:
pdf.savefig(fig)
fig = plt.figure(figsize=(11,7))
j = 1
else:
j = j + 1
pdf.savefig(fig)
## file2.out
fig = plt.figure(figsize=(11,7))
j = 1
for i in range(1,nc2):
... # and it continues like the block of code above
</code></pre>
<p>My questions are:</p>
<ul>
<li>Do I need all those imports and are they slowing down the execution?</li>
<li>Is there a better way to read the data files then opening them twice (once to get the file header and once to get data)?</li>
<li>Am I using the matplotlib commands correctly/efficiently (I am not very familiar with matplotlib, and this is basically my first attempt to use it)?</li>
</ul>
<p>Please keep in mind that ideally this script should have as few dependencies as possible, because it is meant to be used on different systems by different users.</p>
<p>The data files have the following format:</p>
<pre><code> t X1 X2 X3 X4 X5 X6 X7 X8 X11 X12 X13 X14 X15 X16
6.000000E+001 4.309764E-007 2.059219E-004 9.055840E-007 2.257223E-003 1.148868E-002 7.605114E-002 4.517820E-004 3.228596E-008 2.678874E-006 7.095441E-006 1.581115E-007 1.010346E-006 1.617892E-006 9.706194E-007
1.200000E+002 4.309764E-007 2.059219E-004 9.055840E-007 2.257223E-003 1.148868E-002 7.605114E-002 4.517820E-004 3.228596E-008 2.678874E-006 7.095441E-006 1.581115E-007 1.010346E-006 1.617892E-006 9.706194E-007
1.800000E+002 3.936234E-007 2.027775E-004 8.644279E-007 2.180931E-003 1.131226E-002 7.476778E-002 4.353550E-004 3.037527E-008 2.534515E-006 6.778434E-006 1.470889E-007 9.488175E-007 1.531702E-006 9.189112E-007
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:49:05.127",
"Id": "409403",
"Score": "1",
"body": "Can you provide a small example input file for which the code works exactly as intended to demonstrate it's capabilities? This tends to make writing reviews easier, leading to higher quality reviews."
}
] | [
{
"body": "<h1>coding style</h1>\n\n<p>Your code is almost pep-8 compliant. There are a few spaces missing after comma's, but all in all this is not too bad. I myself use <a href=\"https://github.com/ambv/black\" rel=\"noreferrer\">black</a> to take care of this formatting for me.</p>\n\n<p>some of the variables names can be clearer. What does <code>nc1</code> mean for example</p>\n\n<h1>magic numbers</h1>\n\n<p>The number 3, 2 and 6 are the number of rows and columns on the grid. Better would be to make them real variables, and replace 6 with <code>rows * columns</code>. If you ever decide you want 4 columns, you don't have to chase down all those magic numbers</p>\n\n<h1>looping</h1>\n\n<p>You are looping over the indexes of <code>var</code> and <code>df</code>. Better here would be to use <code>zip</code> to iterate over both tables together. If you want to group them per 6, you can use the <code>grouper</code> <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\">itertools recipe</a>. and <code>enumerate</code> to get the index of the different subplots.</p>\n\n<pre><code>rows, columns = 3, 2\n\nfor group in grouper(zip(var1[1:], df1[1:]), rows * columns):\n fig = plt.figure(figsize=(11, 7))\n for i, (label, row) in enumerate(filter(None, group)):\n ax = fig.add_subplot(rows, columns, i + 1)\n ax.plot(df1[0], row, linestyle=\"-\", color=\"black\")\n ax.set(title=label, xlabel=\"seconds\", ylabel=\"\")\n</code></pre>\n\n<p>The <code>filter(None,...)</code> is to eliminate the items that get the <code>fillvalue</code> in the <code>grouper</code></p>\n\n<p>Is a lot clearer than the juggling with <code>nc1</code> and <code>j</code></p>\n\n<h1>functions</h1>\n\n<p>This would be a lot easier to test an handle if you would separate the different parts of the script into functions</p>\n\n<ul>\n<li>reading the file</li>\n<li>making 1 page plot</li>\n<li>appending the different pages</li>\n</ul>\n\n<p>This will also allow each of those parts to be tested separately</p>\n\n<h1>reading the file</h1>\n\n<p>Instead of loading the file twice and using <code>numpy</code>, using <code>pandas</code>, which supports data with names and indices will simplify this part a lot</p>\n\n<pre><code>df = pd.read_csv(<filename>, sep=\"\\s+\", index_col=0)\n</code></pre>\n\n<p>this is a labelled DataFrame, so no more need to use <code>var1</code> for the column names</p>\n\n<h1>making the individual plot:</h1>\n\n<h2>group the columns per 6</h2>\n\n<pre><code>def column_grouper(df, n):\n for i in range(0, df.shape[1], n):\n yield df.iloc[:, i:i+n]\n</code></pre>\n\n<p>this simple helper generator can group the data per 6 columns</p>\n\n<h2>make the plot</h2>\n\n<pre><code>def generate_plots(df, rows=3, columns=2):\n for group in column_grouper(df, rows * columns):\n fig = plt.figure(figsize=(11, 7))\n for i, (label, column) in enumerate(group.items()):\n ax = fig.add_subplot(rows, columns,i + 1)\n ax.plot(column, linestyle='-', color='black')\n ax.set(title=label, xlabel='seconds', ylabel='')\n yield fig\n</code></pre>\n\n<h1>saving the pdf</h1>\n\n<p>Here a simple method that accepts an iterable of figures and a filename will do the trick</p>\n\n<pre><code>def save_plots(figures, output_file):\n with PdfPages(output_file) as pdf:\n for fig in figures:\n pdf.savefig(fig)\n</code></pre>\n\n<h1>pulling it together</h1>\n\n<pre><code>def parse_file(input_file, output_file, rows=3, columns=2):\n df = pd.read_csv(input_file, sep=\"\\s+\", index_col=0)\n figures = generate_plots(df, rows, columns)\n save_plots(figures, output_file)\n</code></pre>\n\n<p>and then calling this behind a <a href=\"https://stackoverflow.com/a/419185/1562285\"><code>main</code> guard</a></p>\n\n<pre><code>if __name__ == \"__main__\":\n input_files = ['file1.out', 'file2.out']\n output_file = 'file_output.pdf'\n\n for input_file in input_files:\n parse_file(input_file, output_file)\n</code></pre>\n\n<p>If this still is too slow, at least now the different parts of the program are split, and you can start looking what part of the program is slowing everything down</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T12:19:34.393",
"Id": "422983",
"Score": "0",
"body": "Thanks, looks great. I am getting an error `'DataFrame' object has no attribute 'items'` which I think is related to the output of `column_grouper()`, but I am not sure I understand exactly what that function does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T12:36:34.530",
"Id": "422986",
"Score": "0",
"body": "[`DataFrame.items`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.items.html). This should work. It worked for me at least. I didn't test the pdf creation, but the plot generation worked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:21:26.447",
"Id": "422992",
"Score": "0",
"body": "Ah, so it should be `for i, (label, column) in enumerate(group.iteritems()):` in the `generate_plots()` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T07:09:10.540",
"Id": "423133",
"Score": "0",
"body": "I think both items and iteritems should work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T12:00:09.837",
"Id": "423175",
"Score": "0",
"body": "thanks a lot, this has been really helpful. The script is part of a larger (open source) program. Are you happy for me to upload this code to github? With proper credits of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T09:45:48.213",
"Id": "423314",
"Score": "1",
"body": "Sure, go ahead."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T12:49:00.450",
"Id": "217735",
"ParentId": "211717",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "217735",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:28:56.527",
"Id": "211717",
"Score": "6",
"Tags": [
"python",
"matplotlib",
"pdf"
],
"Title": "A Python script to plot data and save to PDF"
} | 211717 |
<p>The rules:</p>
<ul>
<li>The points rolled on each player’s dice are added to their score.</li>
<li>If the total is an even number, an additional 10 points are added to their score.</li>
<li>If the total is an odd number, 5 points are subtracted from their score.</li>
<li>If they roll a double, they get to roll one extra die and get the number of points rolled added to their score.</li>
<li>The score of a player cannot go below 0 at any point.</li>
<li>The person with the highest score at the end of the 5 rounds wins.</li>
<li>If both players have the same score at the end of the 5 rounds, they each roll 1 die and whoever gets the highest score wins (this repeats until someone wins)</li>
</ul>
<pre><code>import pickle
import random
import time
print("")
print("welcome to the dice game")
print("")
with open('users.pickle', 'rb') as f:
users = pickle.load(f)
print(users)
def login():
logged_in = False
username = input('please enter username: ')
while not logged_in:
if username in users:
password = input("enter password: ")
if password == users[username]:
print("access granted")
logged_in = True
else:
print("access denied")
exit()
return username
print(" ")
rounds = 0
def roll():
die1 = random.randint(1, 7)
die2 = random.randint(1, 7)
change = 10 if (die1 + die2) % 2 == 0 else -5
points = die1 + die2 + change
if die1 == die2:
points += random.randint(1, 6)
return points
def game():
player1_points = 0
player2_points = 0
for i in range(1, 6):
player1_points += roll()
print(f'After this round user1 you now have: {player1_points} Points')
# time.sleep(1)
player2_points += roll()
print(f'After this round user2 you now have: {player2_points} Points')
player1_tiebreaker = 0
player2_tiebreaker = 0
if player1_points == player2_tiebreaker:
while player1_tiebreaker == player2_tiebreaker:
player1_tiebreaker = random.randint(1, 6)
player2_tiebreaker = random.randint(1, 6)
player2_win = (player2_points + player2_tiebreaker)
player1_win = (player1_points + player1_tiebreaker) \
return (player1_points, player1_win), (player2_points, player2_win)
def add_winner(winner):
with open('Winner.txt', 'a') as i:
i.write(','.join(map(str, winner)))
i.write('\n')
def get_leaderboard():
with open('Leaderboard.txt', 'r+') as g:
return [line.replace('\n', '') for line in g.readlines()]
def update_leaderboard(leaderboard, winner):
for idx, item in enumerate(leaderboard):
if item.split(',')[1] == winner[1] and int(item.split(',')[0]) < int(winner[0]):
leaderboard[idx] = '{}, {}'.format(winner[0], winner[1])
else:
pass
leaderboard.sort(reverse=True)
def save_leaderboard(leaderboard):
with open('Leaderboard.txt', 'r+') as h:
for item in leaderboard:
h.write(f'{item}\n')
def main():
user1 = login()
user2 = login()
(player1, player1_win), (player2, player2_win) = game()
if player1_win:
winner = [player1, user1]
else:
winner = [player2, user2]
print("Well done: ", winner[1], "you won with", winner[0], "Points")
add_winner(winner)
leaderboard = get_leaderboard()
update_leaderboard(leaderboard, winner)
save_leaderboard(leaderboard)
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>Starting off, its not secure the way you are prompting for passwords and storing them. Instead, use the <code>getpass</code> module, and store the hash of the password. I'm not even certain that this way is 100% correct (I'm not a security guru), but its what the Python documentation shows for secure password hashing, and I imagine its better than plaintext.</p>\n\n<pre><code>from getpass import getpass\nfrom hashlib import pbkdf2_hmac as pwhash\n\ndef login(users):\n username = input('please enter username: ')\n if not username in users:\n print(\"access denied\")\n exit()\n\n password_hash = None\n while password_hash != users[username]:\n password_hash = pwhash(\"sha256\", getpass().encode(\"ascii\"), b\"t4h20p8g24j\", 100000)\n\n print(\"access granted\")\n return username\n</code></pre>\n\n<p>Your roll function had a typo in it- the third (optional) roll could only generate numbers [1, 5] inclusive. I also reordered the statements to remove an intermediate variable that didn't contribute anything.</p>\n\n<pre><code>def roll():\n die1 = random.randint(1, 7)\n die2 = random.randint(1, 7)\n points = die1 + die2\n points += 10 if (die1 + die2) % 2 == 0 else -5\n if die1 == die2:\n points += random.randint(1, 7)\n return points\n</code></pre>\n\n<p>I would replace your <code>get_leaderboard</code> body with a shorter and cleaner read call.</p>\n\n<pre><code>def get_leaderboard():\n with open('Leaderboard.txt', 'r+') as g:\n return g.read().split(\"\\n\")\n</code></pre>\n\n<p>And similarly for <code>save_leaderboard</code></p>\n\n<pre><code>def save_leaderboard(leaderboard):\n with open('Leaderboard.txt', 'r+') as h:\n h.write(\"\\n\".join(leaderboard))\n</code></pre>\n\n<p>You should also try to avoid excessive use of tuples when you need to access the elements individually. Your code will be littered with <code>thingy[0]</code> and <code>thingy[1]</code> and nobody but you (if that) will know what the significance of <code>0</code> and <code>1</code> are. I revised <code>update_leaderboard</code> with these changes, but I'm still not quite satisfied with it.</p>\n\n<pre><code>def update_leaderboard(leaderboard, winner):\n winner_score, winner_name = winner\n for idx, item in enumerate(leaderboard):\n item_score, item_name = item.split(', ')\n if item.name == winner_name and int(item_score) < int(winner_score):\n leaderboard[idx] = '{}, {}'.format(winner_score, winner_name)\n leaderboard.sort(reverse=True)\n #leaderboard.sort(reverse=True), key=lambda x:int(x.split(', ')[0]))\n</code></pre>\n\n<p>The data really shouldn't be cast back and forth from strings to lists/tuples so much. It would be best to just make a dictionary of <code>name:score</code> pairs, and write a tiny bit of formatting logic into your <code>get_leaderboard</code> and <code>save_leaderboard</code> functions. I wasn't going to change that much though. </p>\n\n<p>I also want to point out common mistake that could normally create a bug in sorting (in your case it does not because of the hard-coded <code>,</code>, but still)- you can't rely on <code>str.sort</code> to sort a list of strings by their numerical value. I left a comment showing how you would do this correctly if your delimiter evaluated as greater than <code>\"0\"</code>.</p>\n\n<p>Furthermore- you shouldn't really rely on changing <code>leaderboard</code> outside the function scope. I feel like this is partially why you chose to go with the (unnecessary) <code>enumeration()</code> logic. Instead, return the modified leaderboard and allow the caller to take it from there.</p>\n\n<p>Anyways, the last major change I would make would be to move all your globals (and friends) inside your <code>main()</code> function.</p>\n\n<pre><code>def main():\n print(\"\")\n print(\"welcome to the dice game\")\n print(\"\")\n\n with open('users.pickle', 'rb') as f:\n users = pickle.load(f)\n\n print(users)\n print(\" \")\n\n user1 = login(users)\n user2 = login(users)\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-23T11:56:42.470",
"Id": "410036",
"Score": "1",
"body": "thanks and about the security its just a game so I didn't want it to complicated but still nice to know."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T23:23:48.097",
"Id": "211724",
"ParentId": "211718",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "211724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T19:34:16.837",
"Id": "211718",
"Score": "2",
"Tags": [
"python",
"dice"
],
"Title": "Dice game for two players (Nea)"
} | 211718 |
<p>I have 2 list containing some Objects (Fruit class). I am using a 3rd list to add these elements based on following 2 criteria. </p>
<ol>
<li><p>I want every object in the 1st list added to 3rd list. But if I have a matching object in the 2nd list (matching based on id and isChecked), I want to add the object from the 2nd list to the 3rd list and ignore the one in 1st list. </p></li>
<li><p>If I did the switch mentioned on point one, I want to move that object up to the first element of the 3rd list. </p></li>
</ol>
<p>I have it working with following code. But I find it very inefficient. Is there a better way around it? </p>
<p>Bear in mind I have no control over the second list, but the first list is coming from a Rest endpoint and I am currently capturing it as a list. Unsure if I should have opted for a Map. Please advice. </p>
<p>Example:</p>
<p>In the following example, expected list output is [f2, f5, f1, f3, f4] (based on name). </p>
<p>It is cos I have all the elements from the first list. f2 and f5 went in front of the order as they came from second list (they matched elements in first list and had isChecked set to true). </p>
<pre><code>import lombok.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class App {
public static void main(String[] args) {
Fruit fruit1 = new Fruit("1", "f1", false);
Fruit fruit2 = new Fruit("2", "f2", false);
Fruit fruit3 = new Fruit("3", "f3", false);
Fruit fruit4 = new Fruit("4", "f4", false);
Fruit fruit5 = new Fruit("5", "f5", false);
List<Fruit> firstList = Arrays.asList(fruit1, fruit2, fruit3, fruit4, fruit5);
Fruit fruit6 = new Fruit("2", "f2", true);
Fruit fruit7 = new Fruit("7", "f7", false);
Fruit fruit8 = new Fruit("5", "f5", true);
Fruit fruit9 = new Fruit("9", "f9", false);
Fruit fruit10 = new Fruit("10", "f10", false);
List<Fruit> secondList = Arrays.asList(fruit6, fruit7, fruit8, fruit9, fruit10);
List<Fruit> finalList = new ArrayList<>();
// expected list = [f2, f5, f1, f3, f4]
// this loop is checking and adding objects to finalList.
// must match the first list and isChecked.
// in this case, only f6 and f8 matches the first list (id match) and is also 'checked'.
for (Fruit first : firstList){
for (Fruit second : secondList){
if(first.getId().equals(second.getId()) && second.isChecked()){
finalList.add(second);
break;
}
}
}
// not done yet. Still need to loop and add back the elements from the first list
// which were not added in the above loop
boolean addedFirst = false;
outer:
for(Fruit first : firstList){
for(Fruit finalFruit : finalList){
if(first.getId().equals(finalFruit.getId())){
continue outer;
}
}
finalList.add(first);
}
for(Fruit fruit : finalList){
System.out.println(fruit);
}
}
}
@Getter
@Setter
@ToString
class Fruit{
private String id;
private String name;
private boolean isChecked;
Fruit(String id, String name, boolean isChecked) {
this.id = id;
this.name = name;
this.isChecked = isChecked;
}
}
</code></pre>
| [] | [
{
"body": "<p>It sounds like you want the fruits unique to the first list to go at the end of the final list, and the fruits in both the first and second list go at the beginning of the final list.</p>\n\n<p>For a problem like this, it might be better to use a <code>LinkedList</code> instead of an <code>ArrayList</code>, at least for the final list. Usually you're better off with an <code>ArrayList</code>, but in this case you can benefit from inserting an element at the front of the list is an <span class=\"math-container\">\\$O(1)\\$</span> operation instead of <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<p>You're on the right track with using a <code>Map</code> to speed this up with large data sets. Here is a potentially more efficient implementation:</p>\n\n<ol>\n<li><p>Loop over the first list, filling a map <code>firstMap</code> with key: <code>firstItem</code> value: false </p></li>\n<li><p>Loop over the second list, and for each item, insert the result of \n<code>firstMap.containsKey(secondItem)</code> into <code>firstMap</code> with a key of <code>secondItem</code></p></li>\n<li><p>Finally, loop over the first array, if <code>firstMap.get(firstItem)</code> is true, insert the item at the front of the final list (it was in both lists). Else add it to the end of the final list (it was only in the first list).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-28T08:49:59.217",
"Id": "410723",
"Score": "1",
"body": "Linked list is slower than array list up to 10k elements or so when inserting at head. Because of cache coherency and no indirection. Please benchmark before deciding to use linked lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T07:43:20.583",
"Id": "451233",
"Score": "0",
"body": "Really? 10k, not only 10? A reference would be nice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-28T04:28:51.577",
"Id": "212362",
"ParentId": "211719",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-17T20:16:15.237",
"Id": "211719",
"Score": "1",
"Tags": [
"java"
],
"Title": "Efficiently compare 2 lists to replace and order"
} | 211719 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.