instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I've created a Grid with a RecyclerView similar to the GoogleIO 2014's generic media player one. GoogleIO generic music player Mine The thing is that the images doesn't load immediately, but with a delay, so I had to put that "dirty" code for add a crossfade every time an image is loaded. Beside that, I just want the...
stackexchange/codereview
I have the following code that I know can be written in a better way. Basically I query tables and display the results for each student for the homework that has been marked. <?php include 'inc/db_con.php'; mysql_select_db("homework", $con); $resultcourse = mysql_query("SELECT course_code FROM courses WHERE course_ac...
stackexchange/codereview
I have updated my code from the last time it got reviewed. If anyone has some more suggestions on how I can improve this and/or make it faster it would be appreciated! def is_prime(num): '''Calculates whether num is a prime number, if it is return True otherwise return False''' # SPECIALCASE: These are spe...
stackexchange/codereview
I've started learning .NET with MVC 4 in C# and I built a basic application to display records from a MySQL database. It's incredibly basic, but it's the best I could come up with being a complete beginner to C# and all. Most of the programming I do is with Ruby on Rails and I tried to carry over some of the design pat...
stackexchange/codereview
I was doing a problem, SPOJ: FLIB. My code was running slow (getting Time Limit Exceeded error) when I was using Code1. However, my code accepted within the required time limit when I hardcoded the multiplication instead, using Code2. Can someone tell how this was a significant change? Note that this program relies hea...
stackexchange/codereview
I am using a Deep Learning model I trained and want to improve its accuracy by implementing a rolling average prediction. I have already done it but want to improve it as I am making predictions on every 3 frames. Input: Each index represents a class and the respective prediction the model makes. Order is not alphanume...
stackexchange/codereview
I am into building functional prototypes, but also for outputting CSS and JS, which means we have 2 times we build out our code, once as a demo with HTML files (we are using assemble.io) and another, where we are building out the files to be uploaded to production (an Enterprise CMS). Most things about the build are th...
stackexchange/codereview
This post has been answered and updated. This was the first time I've ever written a template class. I've spent probably a bunch of times re-writing matrix code for different types, different functions. I'm looking to make a general library for future work of mine. With that in mind, I'd like to have a nice working o...
stackexchange/codereview
In the following code, I implement a class that starts a process and returns its return code, stdout and stderr. It also has a concept of timeout after which the child process is killed. This class will be used as a part of a multi-threaded application. #ifndef PROCESS_H_ #define PROCESS_H_ //Header #include <chrono> ...
stackexchange/codereview
I'm brand new here, but I've read the guidelines and looked at some up-voted questions. Hopefully I understand how I'm supposed to do this... if not, please let me know and I'll fix my question. Explanation I have written a simple javascript plugin of sorts. It takes the settings object for a jQuery.ajax request and a...
stackexchange/codereview
The idea is to init garbage heap in the beginning of main, use gmalloc, gcalloc and grealloc wrappers and free all allocated memory in the end of main. It helps to avoid memory leaks when writing programs for ejudge systems. Would like to hear general feedback on the idea and advices on how to improve the code (beginne...
stackexchange/codereview
I built a scanner generator like flex or jflex in Scala for a class last year. Part of this project is a small library for handling and manipulating finite automata. It works completely as intended, except for maybe some bugs in the conversion to dot-code, which is of little concern. I would like to have some aspects o...
stackexchange/codereview
I have written a simple JS module "loader" (loader is in quotes because it doesn't actually load the files) that is designed to resolve simple dependencies between modules. It is heavily inspired by module.js and takes some of it's design from it. Here is the code itself: (function() { function create() { var def...
stackexchange/codereview
I built one JavaScript debounce function. I need a JavaScript expert's opinion if this is the correct way to do it, and if not, then what the flaw is in this current function. var debounce = function(inpFun, wait) { var timeout; return function () { if(!timeout) { inpFun.apply(this, argume...
stackexchange/codereview
I'm writing integration for a project, but our framework doesn't provide any ability to inject dependencies, so I've written tests with a unit testing framework (GTest) and used a mock (GMock) in an odd way simply to leverage its behaviour obverving functions. I have a python script to run it, it all works, but, is th...
stackexchange/codereview
I have been trying for so long to code an encryption/decryption algorithm using the modulus operator. Basically my code does a basic mathematical operation on given text and key then do a modulus 255 as in 255 ASCII characters. But I was never able to successfully reverse a modulus operator. I have finally programmed s...
stackexchange/codereview
This is based on this leetcode question. I get the correct answer, but I know it could be much, much cleaner. I also know there is supposed to be an O(n) space solution, but I'm not sure how to implement cleanly. It is a dynamic programming problem, I tried to add some helpful code comments, I know it's pretty messy ...
stackexchange/codereview
Before I wrote this I searched and found a number of solutions that make use of a caching provider to handle a set of items. I felt that was too cumbersome of an approach and set out to create a class that could cache a single value, similar to the way Lazy<T> manages the initialization of a single value. I'm having tr...
stackexchange/codereview
I made this code for simple leveling game. I think this code may have some issues with security. Also, are there some way to make this code more efficient and reliable? For level scaling I will use this method. Should I make lvl, xp and nxtlevel variables to array or is that a bad idea? class LevelingSystem { privat...
stackexchange/codereview
I am using the SICP book. There is an exercise in which you need to create a function that will receive a list as an argument and return a list with the same elements in a reverse order. I know there are more efficient solutions than the one I am going to present. However, I really learn by analyzing things that came u...
stackexchange/codereview
I have implemented Python-style generators within Java. I might be reinventing the wheel here, but I feel that the ability to define a Generator with an anonymous class is the most flexible approach. Here's the relevant code: generator/Generator.java public abstract class Generator<T> implements Iterable<T>, Iterator...
stackexchange/codereview
I am working on an API to return all the possible flight route between point A and B. I have a set of data which includes the flight number, airline, departure airport, destination airport, departure time, and arrival time. Keep in mind I am also catering connecting flights. But the connections can only happen between ...
stackexchange/codereview
I have a function that is able to return the factors of a number that are prime. For example: The prime factors of 13195 are 5, 7, 13 and 29. The function works great, and I was even able to improve it by dividing by just prime numbers instead of all numbers. The problem is it still isn't efficient enough because at 10...
stackexchange/codereview
For continuity, my last question was with adding numbers together with a function call: Example x86-64 program. In this one I've tried to apply the lessons pointed out in the previous answer (stack alignment, using edx instead of rdx where the results will fit). I've tried to comment inline with the code: # We are goin...
stackexchange/codereview
I try to implement a (restricted version of) step function in Haskell. A step functions is a function that is constant on a finite number of half intervals, and mempty everywhere else. (equivalently, one can fill those "everywhere else" by half intervals) This can be modeled as a StepData a b, which stores a list of th...
stackexchange/codereview
So i took even more suggestions and improved the code from this question. Some of the suggestions i wasn't able to implement simply because of my "newbieness" in c++ programming main.cpp #include "app.h" int main() { // Window aspect ratio is always 4:3, so it only takes // a value that is then used as the s...
stackexchange/codereview
I am using the ruby sunspot gem to create a search users function on my site. It works fine and the users controller for the index page where there is a search form is this def index if params[:search].nil? @users = nil else @search = User.search do fulltext params[:search] end @users = @search.results.p...
stackexchange/codereview
Given A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. Solution import time def reverse(num): dreverse = 0 while (num > 0): dreverse = drevers...
stackexchange/codereview
I'm brand new to JavaScript and jQuery and I feel like there's probably a better way to do this. It seems that the way I designed it may not be very optimal once you get a thousand entries in the list but I do like the fact that it's a live search. Note: I tried changing the style of the <option>'s to display:none but...
stackexchange/codereview
I wrote a Mandelbrot renderer in C++ that uses AVX intrinsics to calculate 8 pixels per thread in parallel. It can compute 1080p frames with 256 max iterations in about 40 milliseconds on a 2 core 4 thread i5-6200U laptop. Any advice on performance, code style etc would be appreciated. https://github.com/voldemoriarty...
stackexchange/codereview
I Using Nodejs v9.10.1 for handle download operation from another application. When using PM2 in fork mode to make alive my code. After 50 minutes, this will show high memory usage. Server Config is CentOS v6.9, 6 Core cpu, 8GB memory. Any changes needed on this code or any performance? And here is my nodejs code (down...
stackexchange/codereview
For the purposes of unit-testing in Python, I've written a very simple function for generating variable-length lists populated with random objects: constructors = [ object, dict, lambda: bool(randint(0, 1)), lambda: randint(1, 1000), lambda: ''.join(choice(digits) for _ in range(randint(1, 10))) ] ...
stackexchange/codereview
I need to define an entity (CompositeContactList) that contains and manages two collections of identifiers (IncludedLists and ExcludedLists) that are ids of some other entities (ContactList). The business rules are the following: 1. The collections must contain only unique identifiers. 2. The same identifier cannot bel...
stackexchange/codereview
First time posting to Code Review. Just looking to get some advice on how I can write better code. I found the following exercise for a "Guess my Number" game on DaniWeb, but the linked source code file is no longer active. So while I know my code works, I'm not sure if I've written it in the best way. "The computer r...
stackexchange/codereview
It seems like I'm repeating myself here. Is there a standard way to deal with code like this? def getNameParts(name): """Return a dictionary of a name's parts. name: e.g. 'JOHNSON, John Roberts, Jr. (Jack)' Ignores nicknames. """ csSplit = name.split(', ') try: last = csSplit[0] exce...
stackexchange/codereview
I'm coming from PHP and recently started developing in Python. As a part of my self-study course, I developed a small library for access to Visa Developer Program APIs and published it on Github. It is bundled with demo Django app. Here I'm sharing a module that implements an abstract connection to VDP. I'd appreciate ...
stackexchange/codereview
I have a table called tblStudent having data as I want to retrieve records having single value compared against multiple columns. For example - find all students having Grade 'C' in any of the subjects. One way could be - SELECT * FROM tblStudent WHERE Grade_Maths = 'C' OR Grade_Science = 'C' OR Grade_English = 'C'...
stackexchange/codereview
The code is working but slow. Is there a way to speed it up or make it more compact but still easy to read? There are 35 different jobs to be done. They are made in a worksheet with merged cells to enter, who did the job, when, how long, workorder, nr, etc. Next to the layout is a command button, and when you click on ...
stackexchange/codereview
Given the models below: class Structure(Model): ... class StructureComponent(Model): ... structure = ForeignKey(Structure) parent_component = ForeignKey('self', null=True, ...) Developer should synchronize with the database a list of trees: The sample of request data: { 'trees': [ { ...
stackexchange/codereview
This class is mostly an educational exercise for me using some C++11 constructs. I wanted to create something similar to an "invocation list" in C#, i.e., a list of zero or more function objects which should be called when the invocation list as a whole is invoked. I'm certain there's room for improvement here and I'm ...
stackexchange/codereview
This might be a loaded question, but here goes. I have some code that is very similar between all the methods. I am trying to find a way to accomplish all methods with a generic method/function. I'm not sure if I should be using delegates, and if so how to implement in this specific situation, or if there is a much m...
stackexchange/codereview
Given the problem: You are provided a list of N elements all initialized to 0, and a list of M operations. Where each m in M consists of 3 elements a, b, and k. For each m in M add k to all indices in the range [a, b]. At the end of all M operations print out the max. I have two implementations, one of which is faste...
stackexchange/codereview
I've never been too bothered by the lack of present (and thus print) support for Factor collections and other objects, but I've never needed to generate Factor programs from JSON until now. To that end, I use these methods to turn arrays, hashtables and assocs into roundtrippable strings: M: f present drop "f" ; M: ...
stackexchange/codereview
This uses a linked list to store the data. I used a linked list as it's the only type of data structure that I know currently. Using chrono, I can get microseconds into my timer and <random> for a completely random scramble. A main goal of this program is to be fast in the sense of less keystrokes to get scramble and s...
stackexchange/codereview
Conditional parsing (aka read some tokens and return true or false). As a solution to this SO question, I wrote following code: bool nectar_loader::resolve_conditional( const std::function<bool(const string&)> &config_contains ) { bool result = true; // My very own recursive implementation /* - each s...
stackexchange/codereview
I am solving a problem on Leetcode that requires me to design a hash set. I intend to solve it using linked lists where each linked list would represent a bucket. I am intending to implement this: However, I am failing in one large test case. This is my solution that failed a test case mentioned below: class MyHashSet...
stackexchange/codereview
I am a beginner Java developer, and I am self learning Java by developing a real life business desktop application intended for management in repair shops. It is unimaginatively called Repair Shop Software. You can see the whole project on GitHub here. I just wanted an opinion on my data-structure management class Data...
stackexchange/codereview
I have this switch case statement which maps an integer to a string. There can be multiple integers that maps to same string. objective here is to not to duplicate the string value and retrive the string value by passing the id. public const int Product1 = 111; public const int Product2 = 112; public const ...
stackexchange/codereview
This is code for performing a calculation that should be repeated with different levels and temperatures. I am concerned about the organization of this code as I feel it may contain too many helper functions and seems a little unnecessarily complicated. Only the getCharge() method needs to be exposed to the browser. Th...
stackexchange/codereview
I just finished writing a simple version control. You register files using "add", and then "com" will save them inside a directory, with an ID attached to it, same ID for all files. With "rev" it will copy back the content of the files, but won't delete any file other than the one in the "commitdir". package main impo...
stackexchange/codereview
I'm currently trying to learn how to OOP in JavaScript by making use of ES6 classes. As an example I created this Slider using classes. I didn't find any class example where the DOM is highly involved class Slider { constructor(_options, _className) { this.options = _options; this.container = document.getEl...
stackexchange/codereview
I was searching for a long time how to write multi-page TIFFs with the JPEG encoding. TIFFs support JPEG encoded frames but the built-in encoder in .NET Framework does not have JPEG as a compression option. The code is based on the answer to this question: https://stackoverflow.com/questions/14811496/tiff-with-jpeg-co...
stackexchange/codereview
The code bellow is my implementation for the natural merge exercise in Robert Sedgwick's Algorithms book: Write a version of bottom-up mergesort that takes advantage of order in the array by proceeding as follows each time it needs to find two arrays to merge: find a sorted subarray (by incrementing a pointer unt...
stackexchange/codereview
I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s. To determine the next value of the i-th bit, look at the current value of the bits at positions i−1 and i+1 (if they...
stackexchange/codereview
I'm trying to review this block of code to make sure logic is fine. The first version that I commented will create duplicated order 'my college developer' but I fixed it but "really not sure" I want to make sure my fix it exactly same as commented code the old logic "this code include duplicated" public void setOrdere...
stackexchange/codereview
This is a fixed up version (following RAII principles) of my previous reviewal. I have moved the construction of the object entirely to the constructor to prevent any bad object states. The only thing I am slightly concerned about is if an exception is thrown, the destructor will not be called thus causing shader objec...
stackexchange/codereview
I'm trying to replicate Android's GenerateViewId() to assign a unique Tag to dynamically created UIViews in Xamarin.iOS. internal static class LayoutExtensions { // A tentative to mimmic Java's AtomicInteger used by GenerateViewId() // https://android.googlesource.com/platform/frameworks/base/+/master/core/java...
stackexchange/codereview
I have made a sorting algorithm in Python 3. This sorting algorithm is a modified optimized median of 3 quicksort, with network sorting for lists of size up to 16 and for finding the median. I have tried using the O(N) approach to finding the median, but sorting normally was faster. Can I get some advice on how to make...
stackexchange/codereview
I need a JavaScript-function which always computes the date of the next day. Then returns the date as a string, formatted in the way: dd.mm.yyyy I wrote this code: const getDateStringForTomorrow = () => { const millisOfDay = 1000 * 60 * 60 * 24; const oTomorrow = new Date(Date.now() + millisOfDay); const ...
stackexchange/codereview
I recently completed a coding challenge for a company that did not get me to the next stage. They were kind enough to provide the following feedback: The coding assignment does not match what we are looking for, a mid-level Front End Engineer. The code does not fully comply with what is asked in the assignment and the...
stackexchange/codereview
For an exercise, I've written a function that, given an array of objects and a key (2nd argument), returns a new array of objects that contain all properties from a key. How'd I do? function where(collection, source) { var arr = []; var keys = Object.keys(source); var countMatchingProps = 0; var currentProp...
stackexchange/codereview
I have a question about dependency injection and best practices when using simple classes which are meant to be created often, which have dependencies on external services. Here's a (vastly) simplified version of what I'm working on: app.js import {Factory} from './factory.js'; import {Convert} from './convert.js'; le...
stackexchange/codereview
Earlier I posted a fairly inefficient recursive solution to the problem of getting across a snakes and ladders board in the smallest number of moves. I have created a much faster solution to this using Dijkstra's algorithm and I believe it is correct. Each square on the board is linked to any square that is between 1-...
stackexchange/codereview
This code section is from the main method of my Annual Fuel Use class. The program projects my annual fuel usage based on at least three fill ups of my car. Here, I am calculating the max and min for distance (which is miles traveled), MPG, and price per gallon. I'd like a general review. //initialization of array of ...
stackexchange/codereview
Currently my code (at GitHub) is this: module Gaussian where import qualified Data.Complex as Complex -- Enables toComplex. -- Qualified to avoid clashing. data Gaussian = (:+) { real :: Integer, imaginary :: Integer } deriving (Show, Read, Eq) -- The gaussian integer type. -- A gaussian integ...
stackexchange/codereview
For my programming class, at the start of the semester before we learned about object oriented coding, I was supposed to make a small program that searches through a bunch of files, being graded on useability. from os import walk from time import time SEPARATORS = (" ", "-", "_", ":", "|", "~") REMOVABLES = (".", ",",...
stackexchange/codereview
Just a little exercise to make me more affluent with strings and error handling, any improvements welcome! #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdbool.h> #include <math.h> #define MAXSIZE 1024 void retreiveStringInput(char *str, size_t buffersize) { for (;;) { if (fgets(st...
stackexchange/codereview
I did write the GitHub Auto Copy Committer. The purpose is to copy an existing public GitHub repository to in another repository - commit per commit. It's reason is not a full copy of a repository. There are way easier ways for it. The key feature is the ability to redo the original commit behaviour as the origi...
stackexchange/codereview
I have written a Sudoku app for Ruby. This is my first attempt at coding in Ruby so there are sure to be lots of way to optimise it or make it more efficient. To summarise the code: it takes an input file of a Sudoku problem in the format comma separated row, column, value of the initial Sudoku problem. This is stored ...
stackexchange/codereview
It echoes files or strings to output, never both at once. It does work (in both Linux and Windows), but I can NOT guarantee that it is bug free. It works much like echo, but it works with files as well, and has fewer formal arguments. I'm looking for helpful and useful critiques, mainly in programming style, organizati...
stackexchange/codereview
I have this one single line of code I wanted to improve. My main concern is the execution and rendering speed of it. Even though I am happy with its speed, could it be improved? document.getElementById('my-webpart').style.height = (document.documentElement.clientHeight - 80) + 'px'; The reason I didn't ad any variabl...
stackexchange/codereview
I wrote a program that prompts users to enter one string per line and stores it into an array. It also checks for duplicate entries as data are fed and renames those to become distinct by appending an incrementing number. Imagine that it will be used by a large number of people in some name registration event. I am con...
stackexchange/codereview
I think the best Random Number on the Planet is PI. I wrote a code that generates a list of pseudo-random numbers in Python. Then it treats this list as positions of digits in Pi and then outputs digits at those positions. I am expecting someone to tell me that this method is NOT RANDOM ENOUGH. import random # Read al...
stackexchange/codereview
I implemented a Date based on the Gregorian calendar as an exercise. I'm looking mainly for how to make it more readable and easy to test, but any feedback is welcome. public interface Date { GregorianDate addDays(final long offset); boolean isLeapYear(); int getYearDays(); DayOfWeek getDayOfWeek(); ...
stackexchange/codereview
Description: I would like to sample n_points points from k circles whose radii and centers are given as lists. Note: This is my first question :) And k is not a very large number, usually k<7. My code: I guess the parts where I compute the number of points for each circle, and the for loop can be improved. Perhaps with...
stackexchange/codereview
I was refactoring an ugly piece of code, and I'm unsure if there is a better way of doing this, and whether I'm overdoing it with streams. Basically I get a bunch of columns, which should be grouped by the name of the sheet they belong to, so that I can return a map of sheet names to a set of column names. BTW, I can...
stackexchange/codereview
I currently have an Android Activity that allows the users to select the startDate, endDate, startTime and endTime. Once they click the "submit" button, I will combine the startDate and startTime together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the AlarmManager. So...
stackexchange/codereview
I was trying to to print all subarrays of an array in quadratic time. Here is my code: #include <iostream> #include <vector> int main() { std::vector<int> v; int N; std::cin >> N; //size of array for (int i = 0; i < N; i++) { int x; std::cin >> x; v.push_back(x); } int...
stackexchange/codereview
Write a function that a receives file name of a txt file, which contains unknown number of words of max length 10 each. Print the word with the most occurrences. Assume the input is correct and contains at least one word. Code #define MAX_CHARS 11 int mostFrequentWord(char* filename) { char ch; int i, j, k, occurr...
stackexchange/codereview
I have a collection of full type names where I need to reduce common namespaces. For this purpose I wrote two extensions. The first one explodes each namespace into pieces and the second one removes the first name for as long as all first names are equal thus reducing each namespace. static class Namespace { public...
stackexchange/codereview
I split my implementation of this sequence alignment algorithm in three methods. Where NeedlemanWunsch-method makes use of the ScoringFunction and the Traceback methods. Further I decided to go with two matices. One matrix is for the scoring, the second contains data to make the traceback easier. public static int Scor...
stackexchange/codereview
ERROR: type should be string, got "\nhttps://code.google.com/codejam/contest/3264486/dashboard#s=p2\nProblem\nA certain bathroom has N + 2 stalls in a single row; the stalls on the\n left and right ends are permanently occupied by the bathroom guards.\n The other N stalls are for users.\nWhenever someone enters the bathroom, they try to choose a stall that\n is as far from other people as possible. To avoid confusion, they\n follow deterministic rules: For each empty stall S, they compute two\n values LS and RS, each of which is the number of empty stalls between\n S and the closest occupied stall to the left or right, respectively.\n Then they consider the set of stalls with the farthest closest\n neighbor, that is, those S for which min(LS, RS) is maximal. If there\n is only one such stall, they choose it; otherwise, they choose the one\n among those where max(LS, RS) is maximal. If there are still multiple\n tied stalls, they choose the leftmost stall among those.\nK people are about to enter the bathroom; each one will choose their\n stall before the next arrives. Nobody will ever leave.\nWhen the last person chooses their stall S, what will the values of\n max(LS, RS) and min(LS, RS) be?\nInput\nThe first line of the input gives the number of test cases, T. T lines\n follow. Each line describes a test case with two integers N and K, as\n described above.\nOutput\nFor each test case, output one line containing Case #x: y z, where x\n is the test case number (starting from 1), y is max(LS, RS), and z is\n min(LS, RS) as calculated by the last person to enter the bathroom for\n their chosen stall S.\nLimits\n1 ≤ T ≤ 100. 1 ≤ K ≤ N.\n 1 ≤ N ≤ 10^18.\nInput Output \n5\n4 2 Case #1: 1 0\n5 2 Case #2: 1 0\n6 2 Case #3: 1 1\n1000 1000 Case #4: 0 0\n1000 1 Case #5: 500 499\n\n\nDescription of my algorithm \nI attached a little graphic to show how the algorithm is supposed to work. That's maybe quicker to understand than reading through the algorithm.\n/* \nDefinitions:\n Group = A number of consecutive free stalls, in the beginning there is only one group.\n Layer = A new layer is started when all groups of the previous layer are split up.\n Each layer holds therefore 2^(layer - 1) customers\n e.g. 1st layer: 1 customer\n 2nd layer: 2 customers\n 3rd layer: 4 customers\n .\n nth layer: 2^(n-1) customers\n\n With the above definitions it can be calculated how many layers are necessary.\n (Eq. 1) lastLayer = ceil(log(numberCustomers)/log(2))\n\n To calculate the size of the group, the last customer will be assigned to, the size of the\n groups in the last layer must be calculated. To do so, we need the following:\n - number of stalls in the last layer\n (Eq. 2) custPrevLayers = 2^(lastLayer - 1) - 1\n (Eq. 3) stallsLastLayer = totalStalls - custPrevLayers\n - the number of groups\n (Eq. 4) nbrGroupsLastLayer = 2^(lastLayer - 1)\n - and the number of customers in the last layer\n (Eq. 5) custLastLayer = totalCustomers - custPrevLayers\n\n Thus, the average group size is\n (Eq. 6) avgGroupSizeLastLayer = stallsLastLayer / nbrGroupsLastLayer\n\n Since avgGroupSizeLastLayer will in most cases not be an integer, we end up with two different\n group sizes:\n (Eq. 7) largeGroupSize = ceil(avgGroupSizeLastLayer)\n (Eq. 8) smallGroupSize = largeGroupSize - 1\n\n The last step is to figure out how many large groups are present in the last layer. This can\n be calculated by means of (Eq. 9) and (Eq. 10):\n (Eq. 9) stallsLastLayer = largeGroupSize * nbrLargeGroups + smallGroupSize * nbrSmallGroups\n (Eq. 10) nbrGroupsLastLayer = nbrLargeGroups + nbrSmallGroups\n\n Solving (Eq. 9) for nbrSmallGroups and inserting it into (Eq. 10) leaves us with\n (Eq. 11) nbrLargeGroups = (stallsLastLayer - (nbrGroupsLastLayer * smallGroupSize))/(largeGroupSize - smallGroupSize);\n\n If custLastLayer is smaller than the nbrLargeGroups min and max is to be calculated\n with the largeGroupSize, otherwise with the smallGroupSize.*/\n\n\nImplementation:\n/****************************************************************************************\n Includes\n*****************************************************************************************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <stddef.h>\n/****************************************************************************************\n Defines\n*****************************************************************************************/\n#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))\n#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))\n#define MAX_LINE_LENGTH (80)\n\n/****************************************************************************************\n Structs and typedefs\n*****************************************************************************************/\ntypedef unsigned long long uint64;\n\ntypedef struct TestCase_s\n{\n uint64 stalls;\n uint64 customers;\n uint64 max;\n uint64 min;\n} TestCase_t;\n\n/****************************************************************************************\n Forward declarations\n*****************************************************************************************/\n\nstatic void getTestCases(FILE *fp, TestCase_t testCases[], int nbrOfTestcases);\nstatic int getNumberOfTestCases(FILE *fp);\nstatic uint64 getNumberOfStalls(char line[]);\nstatic uint64 getNumberOfCustomers(char line[]);\nstatic int getLine(char line[], size_t buflen, FILE *stream);\n\nstatic uint64 getNumberOfLargeGroups(uint64 sizeLargeGroup, uint64 sizeSmallGroup, uint64 stallsFree, uint64 totalGroups);\nstatic uint64 getLayers(uint64 customers);\nstatic void calcStallsLeftRight(uint64 stalls, uint64 *stallsLeft, uint64 *stallsRight);\n\nstatic void outputToFile(TestCase_t testCases[], int entries, char *outputFile);\n/****************************************************************************************\n Public functions\n*****************************************************************************************/\nint main (void)\n{\n FILE *fp;\n int nbrTestCases = 0;\n\n char input[] = \"Debug/C-large-practice.in\";\n\n char output[] = \"Debug/output.txt\";\n\n fp = fopen(input, \"r\");\n\n if (fp == NULL)\n {\n perror(\"Error while opening the file.\\n\");\n exit(EXIT_FAILURE);\n }\n\n nbrTestCases = getNumberOfTestCases(fp);\n\n TestCase_t *testCases = calloc(nbrTestCases, sizeof(*testCases));\n\n getTestCases(fp, testCases, nbrTestCases);\n\n fclose(fp);\n\n int currentCase = 0;\n\n while (currentCase < nbrTestCases)\n {\n uint64 stallsToLeft;\n uint64 stallsToRight;\n TestCase_t *curTC = &testCases[currentCase];\n\n uint64 lastLayer = getLayers(curTC->customers);\n uint64 custPrevLayers = pow(2, lastLayer - 1) - 1;\n uint64 stallsLastLayer = curTC->stalls - custPrevLayers;\n uint64 nbrGroupsLastLayer = pow(2, lastLayer - 1);\n uint64 sizeLargeGroup = stallsLastLayer/nbrGroupsLastLayer + (stallsLastLayer % nbrGroupsLastLayer != 0); // ciel\n\n if (sizeLargeGroup == 1)\n {\n stallsToLeft = 0;\n stallsToRight = 0;\n }\n else\n {\n uint64 customersLastLayer = curTC->customers - custPrevLayers;\n uint64 sizeSmallGroup = sizeLargeGroup - 1; // size of small group is always one less than number of big group\n uint64 largeGroups = getNumberOfLargeGroups(sizeLargeGroup, sizeSmallGroup, stallsLastLayer, nbrGroupsLastLayer);\n\n if (largeGroups >= customersLastLayer)\n {\n calcStallsLeftRight(sizeLargeGroup, &stallsToLeft, &stallsToRight);\n }\n else\n {\n calcStallsLeftRight(sizeSmallGroup, &stallsToLeft, &stallsToRight);\n }\n }\n\n curTC->max = MAX(stallsToLeft, stallsToRight);\n curTC->min = MIN(stallsToLeft, stallsToRight);\n\n currentCase++;\n }\n\n outputToFile(testCases, nbrTestCases, output);\n\n printf(\"done\");\n\n return 0;\n}\n/****************************************************************************************\n Private functions\n*****************************************************************************************/\n/**\n * Calculates the number of layers needed for a number of customers.\n */\nstatic uint64 getLayers(uint64 customers)\n{\n uint64 layers = 1;\n uint64 possibleCustomers = 1;\n\n while (customers > possibleCustomers)\n {\n layers++;\n possibleCustomers = possibleCustomers << 1;\n possibleCustomers = possibleCustomers | 1;\n }\n\n return layers;\n}\n\n/**\n * Calculate the number of large groups\n */\nstatic uint64 getNumberOfLargeGroups(uint64 sizeLargeGroup, uint64 sizeSmallGroup, uint64 stallsFree, uint64 totalGroups)\n{\n return (stallsFree - (totalGroups * sizeSmallGroup))/(sizeLargeGroup - sizeSmallGroup);\n}\n\n/**\n * Calculates the max number of stalls to the left and right of the stall in the middle.\n * If stalls is an even number the stall to the left is chosen to base the calculation on.\n */\nstatic void calcStallsLeftRight(uint64 stalls, uint64 *stallsLeft, uint64 *stallsRight)\n{\n *stallsLeft = (stalls - 1)/2;\n *stallsRight = stalls/2;\n}\n\n/**\n * Reads test cases from file and fills them into the preallocated memory\n */\nstatic void getTestCases(FILE *fp, TestCase_t testCases[], int nbrOfTestcases)\n{\n char *line = malloc(MAX_LINE_LENGTH);\n int i = 0;\n\n while((getLine(line, MAX_LINE_LENGTH, fp) != -1) && (i < nbrOfTestcases))\n {\n testCases[i].stalls = getNumberOfStalls(line);\n testCases[i].customers = getNumberOfCustomers(line);\n\n i++;\n line = malloc(MAX_LINE_LENGTH);\n }\n free(line);\n}\n\n/**\n * Number of stalls is the first number in a line\n */\nstatic uint64 getNumberOfStalls(char line[])\n{\n return atoll(line);\n}\n\n/**\n * Number of customers is the second number in a line\n */\nstatic uint64 getNumberOfCustomers(char line[])\n{\n int i = 0;\n while(line[i] != ' ')\n {\n i++;\n }\n i++;\n\n return atoll(&line[i]);\n}\n\n/**\n * Number of test cases is the first line in a file.\n */\nstatic int getNumberOfTestCases(FILE *fp)\n{\n char *line = malloc(MAX_LINE_LENGTH);\n\n getLine(line, MAX_LINE_LENGTH, fp);\n\n return atoi(line);\n}\n\nstatic int getLine(char line[], size_t buflen, FILE *stream)\n{\n int i = 0;\n char c = getc(stream);\n\n if (c == EOF)\n {\n return EOF;\n }\n\n while(c != EOF && c != '\\n' && i < buflen)\n {\n line[i++] = c;\n c = getc(stream);\n }\n\n line[i] = '\\0';\n\n return 0;\n}\n\n/**\n * Writes the test results to an output file\n */\nstatic void outputToFile(TestCase_t testCases[], int entries, char *outputFile)\n{\n FILE *fp;\n fp = fopen(outputFile,\"wb\"); // read mode\n\n if (fp == NULL)\n {\n perror(\"Error while opening the file.\\n\");\n exit(EXIT_FAILURE);\n }\n\n for (int i = 0; i < entries; i++)\n {\n fprintf(fp, \"Case #%d: %I64d %I64d\\n\", i + 1, testCases[i].max, testCases[i].min);\n }\n\n fclose(fp);\n}\n\n"
stackexchange/codereview
I wrote a script with utilities for calculating the entropy of iterables and included a Tk GUI that shows a quick overview over a text's properties in real-time. (on GitHub) I tried to follow PEP 8 as good as possible, but I'm not sure about other things, specificially: I think my docstrings are sometimes overly redun...
stackexchange/codereview
Maybe a somewhat odd choice of language, but here is a program in ><> I have tried to optimize the execution time of. (Not golfing). The efficiency is measured in the number of required instructions on an ideal ><>-machine, which uses the same amount of time to execute each instruction. The program does a complete fac...
stackexchange/codereview
Here is my clone pointer template: #include <functional> #include <utility> #include <iostream> template<typename T> struct clone_ptr { clone_ptr() : ptr(nullptr), cloner(nullptr) {} clone_ptr(clone_ptr&& other) noexcept : clone_ptr() { swap( other ); } clone_ptr(const clone_ptr& ot...
stackexchange/codereview
I have a code where the goal is to give score to strings based on how much score certain substrings are worth (including repeating substrings). The way my code (which is based on the Aho-Corasick algorithm) works is: Creating a tree-like data structure where each node represents one prefix of a string (or the full str...
stackexchange/codereview
I'm building an iOS app for test-taking and I want to be sure of my model before proceeding. I found this post very helpful and tried to implement a simplified version for Core Data. Here are some of my assumptions: Each User can take multiple tests Each User has one set of answers per Test taken Each Test has one...
stackexchange/codereview
As part of an exercise I've written some code to generate multiple HTML files based on information stored in a couple of XML files. I'm not really sure how much code you'd need to evaluate my function so this is most of the relevant code regarding the actual HTML from XML generation: # search taxonomy.xml for nodes w...
stackexchange/codereview
I've been tinkering around with making a fancy clock on a Raspberry Pi B. This little application will sync the Pi's time with an NTP server, then display it using toilet so it's nice n' big & centered on a monitor. This was made for a GUI-less Pi, and I'm looking to hopefully make it more efficient. Right now the seco...
stackexchange/codereview
I want to use JavaFX as a solution to Java's issues with buffered input making things like 'press any key to continue' not easy. I plan to use an event listener to detect keyboard input. But before I start down that road I want to know if this is on the right track. Is the code below a good way to use JavaFX to impleme...
stackexchange/codereview
first time posting here, as well as being new to coding in Java. I am trying to create a movie queue with an array that is able to contain 100 elements, but will only read and print the elements the user enters. I got the first section where a user enters a movie and it stores it and prints it working properly, I am ju...
stackexchange/codereview
I need to first filter items for an array of objects {type: 'genre', value: '123'} and after combine in a string content for property value only. Any suggestions on how to improve the following code? this.flattenCategories = function () { // flatten in a single string all categories so to be easily visaulised in th...
stackexchange/codereview
I have an array of objects that I must sort based on two criteria. I've come up with a solution but I'd like to know if there is a better way to do it. Assume a list of devices: [ {"battery_level": 0.45, "network_status": "ok"}, {"battery_level": 0.45, "network_status": "ok"}, {"battery_level": 0.50, "netwo...
stackexchange/codereview
How can I simplify and optimize this code? if type(variant_list) == dict: style_color_if(variant_list[style_colors_main], variant_list) else: for variant in variant_list: if type(variant[style_colors_main]) == dict: json_key_getter(variant[style_colors_main], variant) else: ...
stackexchange/codereview
To practice my C, I've written a small function in C to display an integer as an 8-bit binary number. Please let me know how to improve this function, and other C-style coding conventions. Thanks! /** * Converts an integer to binary. * * @param num Integer to convert. * * @return c-string. **/ const char* to_bin...
stackexchange/codereview
I have a class in which I am passing certain parameters through the constructor and then using those parameters to make one final byte array with a proper format (header + data): public final class Frame { private final byte addressedCenter; private final byte version; private final Map<byte[], byte[]> keyDataHol...
stackexchange/codereview
Can anything be improved in this code? #include <iostream> using namespace std; void print(int *a, int n) { int i=0; while(i<n){ cout<<a[i]<<","; i++; } } void swap(int i,int j, int *a){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } void quicksort(int *arr, int left, int right...
stackexchange/codereview
I have the following code and it's taking quite some time to run. I'm getting an Out of Memory Exception due to the high volume of answers there are. Is there any way I could speed it up? var controlStrings = answerControlStrings.Where(a => a.ControlN.Substring(a.ControlN.IndexOf('_') + 1, a.ControlN.Length - a.Contro...
stackexchange/codereview
Given the following data struct: typdef struct lista { int num1, num2; struct lista* sig; } nodoNum ; and a declared nodoNum pointer variable, the following function will take said variable and create nodes, link them and stop when the user inputs "0" as the first number and return a pointer to the first node ...
stackexchange/codereview
These functions will open a relative path, read or write to the file, then close. The purpose of these functions is to avoid duplicate code patters for accessing different files that only require one read/write prior to closing. Concerns: Should the functions log errors? Or conventionally is this a job for the caller?...
stackexchange/codereview