instruction stringlengths 71 71.9k |
|---|
So I implemented a simple vec2 and vec3 classes, I wanted to know what remarks you guys can give me to improve it.
I try to work with c++11 and 14 so remarks on that also will be really great.
I tried to support move semantics but I don't really know if I did a really good job at it.
You can create a simple vector like... |
I have designed a C++/CLI wrapper library that allows C++ applications on windows, and other platforms that can load C dlls (e.g. Java via JNA or Python) to make calls to my .Net library.
I was wondering if my dll import/export header, which will be used by external developers, complies with the current "best practice... |
I have tried to write a more user-friendly AES CTR wrapper with PyCrypto, but I'm not sure if it's safe enough. I mean, by default there is IV=1 for CTR and in documentation it's said that IV is ignored anyway, so I'm not sure if I should use it or not (or if it's even necessary rather than overkill).
This code should ... |
Based on suggested reviews for Function to lock a file using memcache, I have modified the code to
import os
import shutil
import memcache
def addToCart(filename, username):
ableToLock = memcache.add(filename, username)
if ableToLock:
# "ableToLock" can happen if the file is still present
# or... |
Below is a netstring parser I wrote in Common Lisp. The docstring contains the usage and return.
(defun parse-netstring (netstring acc)
"recursively parses netstring of the form
size1:string1,size2:string2,size3:string3,
acc can be any list, or nil
returns -> (string3 string2 string1)"
(if (equalp netstri... |
I made a binary search tree implementation in C++ for my personal use in programming competitions.
#include <iostream>
using namespace std;
struct Node {
int key;
Node *leftnode;
Node *rightnode;
string value;
};
Node root_node; // Binary search tree
string inline query_bst(const int key) {
Nod... |
Another one for some late night snack. - Knight's tour!
Please provide your suggestions/flaws/optimization to this knight's tour backtracking code..
package com.komal.backtracking;
import java.util.concurrent.TimeUnit;
public class KnightsTour {
static int size = 6;
static int[][] chessBoard = new int[size][... |
I have a function which is used to convert text (a CHANGES file) into HTML for reading. The function is essentially line-based: if the line is of this type, do this thing; if some other type, do that thing; etc. Further logic needs to be added before the fallback
b.WriteString("<p>" + line + "</p>\n")
but I wanted to ... |
I wrote two template functions to take an integer type and output a float in the given range. One function takes signed integers and the other takes unsigned integers.
The functions are used to normalize audio PCM data into a range that an encoder is expecting, such as [0.0f, 1.0f]. The source audio data can come in ma... |
I'm writing a Caesar Cipher. To deal with characters being shifted to outside of the "normal" printable ASCII range ([32 126]), I'm having them "wrapped" to the max/min in the range.
My current solution works, but it has a couple issues:
It involves a couple repeated lines. The (- max-code (rem (- max-code char-code) ... |
So, I took a stab at the ole C# Card Shuffle. I wanted to create my own genuine solution rather than copy someone else's. Any advice?
public class Program
{
enum Suit
{
Hearts,
Diamonds,
Clubs,
Spades
}
class Deck
{
public List<Card> Cards { get; set; }
... |
I'm learning C++ and thought I would try my hand at writing a basic program in modern C++. I'm always looking for ways to reduce my code to STL algorithms and simplifying areas that would require refactoring. I'm also trying to make my code as readable as possible.
Limitation
I can't modify the precision in std::to_s... |
In my company I follow the following workflow. (I think it can be defined a kind of 'Continuous Integration'.)
Workflow:
We have 3 fixed branches (staging/master/production)
Every push to staging or production automatically deploy to staging/production server.
We use git in the following way:
(suppose I'm working ... |
Given a graph \$G = (V,E)\$ with a unique labeling of each vertex, let the transposition \$(i,j)\$ (where \$i,j\$ are the labels on adjacent vertices) represent selecting an edge and swapping the labels \$i\$ and \$j\$.
I would like to take a list of edges in a graph (a cube in this code), and determine the number of p... |
I am trying to find the similarity between the two movies using Pearson correlation coefficient. The programs is working well for small inputs but for large inputs (like 100000 lines) it takes forever. My professor said it would take few minutes, but my program is executing forever.
The input format: user|movie|rating.... |
The first Python class below is used in one of my current projects and is a totally different approach to how I normally would take things. Before I refactored the class I was not declaring instance-properties/variables. Instead the whole update procedure took place inside the def update(self): method (see: "The 'old s... |
Recently I asked a question on Programming SE about public vs private methods fo unit testing, which generated a lot of interesting responses.
I only posted a skeleton of the code there, as it was a question about structure and not about the code itself. However, several respondants queried whether my code might be ove... |
I was writing the below section of code which adds some user properties to an Active Directory user, and got wondering - surely we can improve the readability of this :
var firstname = newUser.FirstName;
var lastname = newUser.LastName;
var email = firstname + lastname + "@mydomain.com";
var dotname = $"{firstname}.{l... |
Building complex applications can sometimes be a pain when extending or editing later on; I read online about the S.O.L.I.D principles of OOD, I want to understand if I am following a good approach that I can follow when developing the rest of the app.
I need answers to the following questions
Is the code well-documen... |
This is a Swift program I wrote to calculate the sum of primes below 2 million, but it is tediously slow.
I am curious about what makes it so slow. My theory is that copying the filtered array is the heavy operation. Any other ideas on how to speed it up?
func initArray (p:Array<UInt32>) -> Array<UInt32> {
var ... |
Problem:
I have seen a few questions around hangman. Usually this is done in a very hackish way, which usually can not be generalized any further. My thought or question is about the creation of the gown, which is a central part in any hangman game.
I want to create the ASCII image below
_____
| |
O |
/|\ |
/ \... |
I have this tiny library for measuring the execution time in milliseconds and returning the duration plus the result:
execres.h
/******************
* File: execres.h *
******************/
#ifndef EXECRES_H
#define EXECRES_H
#include <sys/time.h>
typedef struct {
unsigned long long millis;
void* ... |
I'm implementing an interface to the Force.com REST API, with very specific ideas about which parts of the API I need. My problem is with testability of consumers of this API abstraction.
The first thing I came up with was a Gateway, one method per action:
interface SalesforceApiGateway {
fun getLastUpdated(type: O... |
This is my first attempt at a Model-View-Presenter pattern Winforms application. The model is a class that stores a bunch of primitives, and the view is a Form that provides a ListBox for selecting individual Data items, whose members are then displayed in text boxes.
DataModel.cs
using System;
using System.Collections... |
I started to write a library for linear algebra for personal use, but also for revitilization of my C++.
Below is the first class of this library, a templated vector class, which is templated over the type of the elements as well as the size. It supports all common operations of vectors as member functions and also as ... |
The problem can be found here.
The file, poker.txt, contains one-thousand random hands dealt to two
players. Each line of the file contains ten cards (separated by a
single space): the first five are Player 1's cards and the last five
are Player 2's cards. You can assume that all hands are valid (no
invalid c... |
This is one of the projects on freecodecamp. I would like a review on my code. Thanks in advance.
Javascript:
var answers;
function formatSearchString() {
var searchString = document.getElementById("searchBar").value;
var words = searchString.split(" ");
searchString = words.join("_");
return searchString;
}... |
I have written this class which sorts the array using bubble sort. Please let me know how can I improve it. (I don't like recurrent code in if/else statement)
public class BubbleSort {
public static void numbers(int[] array){
numbers(array, '<');
}
public static void numbers(int[] array, char direction){
if(d... |
I'm looking for feedback on the readability of my code and opinions on the pick_best algorithm. I do this stuff for fun when I have time, and never get a chance to have anyone else look at it. Hopefully, I can use this site to improve my coding.
from itertools import permutations
from random import randint
class TTT... |
I have a table that holds a user's weight for specific days. In my weights_controller.rb index action I can show these weights - no problem. What I also want to show on the index is the user's current weight, his weight loss over time as well as the timeframe he achieved this weight loss.
Thus I created a weight_calcul... |
I am building out a binary expression tree and shown below is an implementation of the tree's node.
The node can be either a leaf or non-leaf, with leaves having Integer type values and non-leaves having ExpressionTreeNodeOperands type values. Leaves may have neither left nor right child nodes, and non-leaves must have... |
The problem:
Making a simple hangman game. This is a continuation of the following question: The right way to hang a man. There I just tried to make the ascii-gallow. Now I have tried to write the rest of the code for the hangman game, using the ideas from the answer.
I have tried very hard to produce the following ou... |
I have an action method in my Rails controller which filters an ActiveRecord model depending on the submitted GET parameters.
Rubocop complains that Assignment Branch Condition Size is too high: 20.62/15.
Is there a way to improve the following code?
@measurements = Measurement.all
@measurements = @measurements.where(s... |
Up-to-date Version of this question: Binary protocol variability V3.0
Summary of the problem: Parsing an incoming stream of events from a binary communication protocol, if we have some variations in devices to support and would not like to have one huge switch to include everything.
So, we use it this way:
static v... |
This is the latest edition of my PDF tool, previously mentioned here, here, here, and inspired by my first attempt at a MVP here.
Major differences from previous editions:
It uses the MVP pattern (as opposed to the god-tier UI that did everything).
The background/separate thread is gone. I will consider adding it back... |
This script prints the weather (fetching the information from a public API).
If anyone could review my code and answer my question about code structure and how should I code in the right way, I really appreciate that very much.
Questions:
I used many functions to do just one specific things, and return their value to ... |
I am able to save my GridView layout by storing a string representation of the items in the ItemsSource. I then load that string representation from the SettingsService and set the index of the items accordingly.
The layout is changed by drag/dropping items in the GridView. Here is the code-behind:
private void MainGri... |
What do you think about this API for loading OpenGL textures asynchronously?
My main concern is that the loader class executes code on the client io_service. This takes away some control from the user but should be convenient in most scenarios.
I'm also thinking about using a texture on the stack and a shared_ptr that ... |
I'm currently creating a utility that is heavily AJAX orientated. I have a page called ajax.php which is handling all POST requests. It switches by the provided command, checks all the arguments exist then passes it off to the relevant class e.g.
case 'addperson':
$name = $_POST['name'] ?? die('{"result":0, "data":... |
I am learning fundamental data structures, and I want to know if this is a valid implementation of a heap. Can any C# features be used to improve or extend the implementation? In addition to heapsort, what are some applications of a heap?
class BinaryHeap
{
/// <summary>
/// A binary heap implementation use... |
So I made this calculator the other day as a small project. I just wanted to know if I remembered the fundamentals. It works fine from the looks of it, but I know there are always ways to improve.
package Main;
import java.util.*;
public class calc {
@SuppressWarnings("resource")
private static void circle(... |
This code reads text files from some path, tokenizes, removes stop words, lowercases, removes punctuation and numbers, then writes the result to a database.
# -*- coding: utf-8 -*-
from __future__ import print_function
import os, codecs, re, string, mysql
import mysql.connector
'''Reading files with txt extension'''
y... |
I have this mergesort implementation that has exactly the same API as qsort:
mergesort.h:
#ifndef MERGESORT_H
#define MERGESORT_H
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
void my_mergesort(void* base,
size_t num,
size_t size,
... |
I'm currently working on a galaxy generator, and I was in need of getting the next that a random would use, for continuing the generation without using a blank generation (re-run previous generation).
I made this little PHP class to do that and implemented a float rand() method.
Please provide advice on improvements.
<... |
This C code will run on an embedded machine with a Linux OS. It should create data packets (ASCII) to repeatedly be sent to a UDP server.
Just to give an overview about what functions should do:
int heartbeat_processopts(struct secs *hbsec)
Reads a settings file and fill a data structure with some options/configura... |
Project Euler Problem 8 asks:
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
Is there any better way to make my code more efficient?... |
See the next iteration: Bare bones painter app in Java - follow-up.
I have this tiny program for drawing:
PaintCanvas.java:
package net.coderodde.javapaint;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.Mou... |
I have an object which stores an app configuration in an associative array, as this:
[
'Database' =>
[
'DB_SERVER' => 'localhost'
'DB_NAME' => 'adbname'
'DB_USER' => 'theuser'
'DB_PASS' => 'thepass'
]
]
It could have more than two levels.
And a function, get(), which receives a varia... |
I have written a program that takes a linked list and then converts it to a stack.
I would like a code review for my program. Thanks in advance.
Stack.java
/**
* Created by Ninan John J P on 2/8/2016.
*/
public class Stack {
int stackArray[];
int topOfStack=-1;
LinkedList source;
int stackSize;
... |
This is code to merge two sorted linked lists. l1 and l2 are sorted. While calling the merge function via l3, I am passing l3 as an object by reference in that function. The code is running fine, but can someone suggest how I can code better, with regards to dealing with class objects and passing them in a function?
#i... |
I have the following construct for storing and restoring my applications settings to and from XML.
public interface ISettingsProvider : ICustomXmlSerializableObject
{
void RestoreDefaultSettings(bool force = false);
}
where I use a wrapper for the XmlSerialization to prevent access from multiple threads at the sa... |
This is an "entry" I made for the June 2016 Community Challenge to make a Chutes and Ladders generator. It generates a random number of chutes and ladders with a total delta of -50 and displays their start points, endpoints, and deltas.
Some notes:
The number of chutes must be at least 2, and the number of ladders at ... |
I am trying to create a simple Hangman game. The game has an edit mode for first run in which the user has to supply 6 unique words. The game starts by shuffling words, then for every turn, it selects one word that the user has to figure out. The user has only 6 tries to get it right for every word.
How can I improve i... |
I'm very new to Erlang and I'm specifically interested in making my Erlang idiomatic (in other words, can you tell I don't know Erlang from this code?) and removing code duplication. I am not as interested in performance or the UI of the "game."
This is a simple interactive Rock, Paper, Scissors game and I've been usin... |
Edit 13 June:
I have made a new and improved version here.
Original Question
This is a very rudimentary lolcats translator (it only works on the phrase "Can I have a cheeseburger") in Haskell. This is my first ever attempt at Haskell (or any functional programming language). I am sure that my code is absolutely atrocio... |
I feel as if my scenario is fairly simple but that I might be overcomplicating it.
I am searching through files looking for a special condition, that is where the method .all with arguments exists. In the real world that looks like:
ba_mbn_programs = Program.ba_and_managed_bar.all(:conditions => "user_programs.user_... |
I am new to Android development and I want to ensure I'm learning decent practices for doing things. Right now this is my database class, which currently allows me to make a new instance of the singleton, as well as create a profiles table, as well as add/retrieve from the profiles table.
This is my code so far:
publ... |
I have the following scenario that I have not come across so far using Ninject. I have the following class structure (simplified for easy of reading :]). First the abstract base class for all IDocuments
public abstract class DocumentController : IDocumentController, IDisposable
{
...
private IMessageBoxService ... |
This is the first time I'm dealing with C# as I'm accustomed to Java sockets, so I do want your full review and anything you think I can accomplish better or optimize in the code will be very appreciated.
In these few classes what I have tried to accomplish is a login and registration server based on C# .Net working as... |
I have been writing PHP for a number of years but in a procedural style. I have always shied away from object oriented PHP because I just didn't understand it. However now I'm back for another go.
I have a large web application which is written in procedural style PHP and as a learning exercise I would like to re-write... |
Some code that I wrote and broke into 5 separate questions on stack overflow. Some guy wanted to query Google Maps receive some JSON and then for each result found within that JSON do another query. I didn;t quite understand what he wanted at first and so actually there is some superfluous code here but I thought it ... |
I am new to Java so go easy on me, here is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication3 {
public static Node root;
ArrayList<Integer> solutionpath = new ArrayList<>();
public JavaApplication3(){
this.root = null;
}
public void insert(int id){
Node newNode = new Node(i... |
I have a situation where I need to predict the input values for a form used to create a new model. The model is a "class report" that a teacher submits for a student after their class finishes and the values of the report I need to predict include the time the class started and finished. These are to be predicted based... |
Summary: Parsing an incoming stream of events from a binary communication protocol, if we have some variations in devices to support and would not like to have one huge switch to include everything.
Previous binary protocol variability V2.0.
This version is way simpler and shorter. Also I removed all the interfaces and... |
Inspired by this blog I went on implementing my own version as a F# learning challenge. It turned out to be quite different than the original (but somewhat faster for large samples).
The first code part below defines some test types and function delegates:
namespace FSLib
open System
// Test Type: Indexed Point in pla... |
I have a function for applying gravity forces between every possible pair of bodies on my game. It is the most used function, and can run more than 100k times per frame so every minor improvement on performance will make a HUGE difference here.
I replaced some divisions by multiplications and the general FPS increased ... |
Today I had to write a small tool to help me send HTTP requests in bulk. Rabbit was overloading my server, so I decided to change my consumers to buffer the contents of the request, before sending. After changing my API, I did this:
#include <amqpcpp.h>
#include <amqpcpp/libev.h>
#include <ev.h>
#include <cpr/cpr.h>
t... |
Imagine you have a call center with three levels of employees: respondent, manager, and director. An incoming telephone call must be first allocated to a respondent who is free. If the respondent can’t handle the call, he or she must escalate the call to a manager. If the manager is not free or not able to handle it, ... |
I wrote a simple Pomodoro Timer in Python 3:
from datetime import datetime, timedelta
from gi import require_version
require_version('Notify', '0.7')
from gi.repository import Notify
import sys
class State:
#length: the length of the state in minutes
def __init__(self, length):
if not length == None:
... |
I've recently started working with Elixir and am writing an app that queries various URLs and parses the response. I am having issues with my parse method, which is included below. The code works just fine, but I am concerned that I may have taken pattern matching too far. The method signature looks like spaghetti.
Thi... |
I have following code in QT in
// myEditor.h
class myEditor : QScintilla {
public:
readFile();
};
#include "myEditor.h"
// myEditor.cc
myEditor::readFile() {
FILE* fp = fopen("mynew.v","r"):
QTextStream ts(fp, QIODevice::ReadOnly);
/* reading the text stream buffer by buffer
bufferSize is c... |
I have made a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.
#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <array>
#include <map>
#include <limits>
namespace
{
enum Winner { Tie, Player, Computer, WinnerCount };
enum Items ... |
I want to extract the creation of different objects in a factory class for the reason of reusability. The problem is that within the current code the objects are configured also for the specific problem. Now I want to reuse only the creation of the objects within another code place.
if (FieldConfiguration.FIELD_TYPE.T... |
I'm learining JS. I have prepared a simple color flooding game, like Pixelated.
The engine below works, though scoring is not implemented. Please help me find out how this code could be made better, more idiomatic JavaScript, or more efficient.
// global variables
var canvas = document.getElementById("game");
var co... |
See the previous iteration: Bare bones painter app in Java.
I have improved my program thanks to all the answers in the initial post. Now I have this:
App.java:
package net.coderodde.javapaint;
import javax.swing.JFrame;
/**
* This class implements an application for simple drawing.
*
* @author Rodion "rodde" Efr... |
I want a mechanism for specifying arbitrary order of type conversion for arbitrary set of types for each operation on that types (separately).
For example, let's have set of types Bool, Date, Number, String and operations isEqual and isLess.
For isEqual I would like to have order Bool -> Date -> Number -> String and fo... |
I'd like to have a discussion on the data model (mostly) for a tree with nodes having multiple children and multiple parents.
I already have a working algorithm, but I'm looking for improvements.
The things to keep in mind are the feasibility of the algorithm and the performances. Here is the data I'm using currently:
... |
I created a class to add functionality to c++ std::string (std::basic_string actually), let's call it String.
I would like to know, what changes to do to String to boost it performance. Maybe having an internal std::basic_string member is not the best idea and it would be better to implement my own (that maybe would be... |
So here is the ugliest fragment of my application, I tried to reformat as much as I could but I think it's still pretty ugly.
Basically, I'm trying to use an API call to receive JSON which tells me what type of field to create dynamically (Edit text, checkbox, Multiple choice, single choice). And then, I add them dyn... |
I created a web service which can be called from a form to add new users to the system. The final service will add users to Active Directory and Exchange in the required format (please note that FirstName and LastName are required fields in the form, so they will never be null):
using System.Collections.Generic;
using... |
Problem Statement
Consider a rover and a plateau of size nxn. The rover takes three type of instructions L,R and M. 'L' and 'R' rotate the rover in the left and right direction. 'M' moves the rover one step forward in the direction it faces.
Input: Plateau size, Initial direction, Initial position and Instructions.... |
I have an abstract class Player, which plays several games of Roulette (samples). For each game, the desired player is cloned into a session method.
for (int i = 0; i < samples; i++)
{
IList<int> sessionStakes = this.Session(player.DeepClone() as Player);
this.maxima.Add(sessionStakes.DefaultIfEmpty(0).Last());... |
I'm a very new to CUDA, so I'm still trying to understand how to make the best use of the GPU. I've ported a C algorithm to it. This algorithm works by loading the memory with an initial input, then calling a rewrite function, which rewrites 128 bits of memory, consecutively, until we arrive at an answer. Since rewrite... |
I'm in the process of converting a custom UIButton from Objective-C to Swift which has custom properties and default values for those properties:
MyButton.h
@interface MyButton : UIButton
@property (nonatomic, strong) IBInspectable UIColor *buttonColor;
@property (nonatomic, strong) IBInspectable UIColor *buttonSelect... |
Following yesterday's advice on my Customer class, I have now created a new class which is for looking up descriptions from a MySQL database. I have a Lookup table which contains type, name, value, and descriptions.
Here's a basic example of type = customer and name = state
Customer States
New Customer
Pending Appro... |
First full program in C++. I'm having trouble understanding when I should use classes and when I should not. Ultimately, after this review, I would love to have a better idea of what circumstances I should use classes and how I can more efficiently write in c++.
I plan to rewrite the program using classes and re-pos... |
I am practicing classes and subclasses in Python. I'm not sure whether it might be useful to add a subclass to the following code, instead of just adding methods to the class.
# Practice with classes
class ElixerTroops(object):
def __init__(self, name, dps, life, special):
self.name = name
self.dps ... |
This is my submission for the June 2016 Community Challenge. It is R code that takes as input the number of squares on the board, the desired number of chutes and ladders, and the desired total sum of the chute and ladder deltas. It then samples uniformly at random from all feasible boards with these properties to retu... |
I am implementing fundamental data structures in C# while trying to learn techniques in the language to make my code cleaner, more concise, and reusable. I have implemented a generic graph with a few elementary search algorithms. What are some ways to improve my implementation and coding style?
/// <summary>
/// Implem... |
Inspired by the StackOverflow question Auto-increment release version Jenkins I developed the following generalized solution.
Is there anything that can be done better, shorter, more elegant, more performant, etc.?
release.cmd
::
:: GROM - Generalized Relase Order Management
:: release.cmd - A script to create a releas... |
This is probably my third Go application. It essentially takes one or two command line arguments of wikipedia articles and pulls every /wiki/ link that isn't a special page, memoizes them to avoid loading the same page twice, and sees how many 'clicks' it takes to get from the first article to the target article.
As t... |
This is a script I made for the ESP8266 that uses the Wi-Fi chip and creates a new Access Point every 5 seconds in order to display a message on WiFi lists on nearby devices that looks like this:
The code is:
#include <ESP8266WiFi.h>
const char* ssids[] = {"Never gonna give you up","Never gonna let you down","Never g... |
I submitted the following Python 3 code for this HackerRank challenge. Given an n × n grid with an m in the center and a p in one corner, it prints the directions to move the m to the p.
I wanted to know how improve it or other observations.
#!/usr/bin/python
def displayPathtoPrincess(n,grid):
#first, find where p ... |
I'm wondering how I can make this function better, more compact, even faster.
char* DectoBin(int dec) {
int counter = 0;
int x =0;
while (dec>=x) {
counter++;
x = pow(2, counter);
}
//counter is the # of bits in the converted binary number
char* bin = new char[counter+1];
//... |
I'm building a framework for comparing files (in my own way) using JUnit. All test cases have been packaged in a JAR which is ran independently using a .bat file I wrote. I needed to output the test results in a file instead of the console.
I was just using normal System.out.println() in the TestRunner class and also i... |
I have written a script that checks if data is known in memcached, and if not it queries it from the mysql db and stores it.
I would appreciate any inputs if i have done this the "correct" way, since i'm trying to optimize the code as much as possible.
_query() & _rows() are simple mysqli functions
Save in memcache
/... |
I created a function that will tell me how many times a number is divisible by another number and what the remainder of it is:
<?php
function divisible_times($number, $divider) {
$count = 0;
$remainder = $number % $divider;
$num_array = range($number, 1);
foreach($num_array as $num) {
if($num %... |
I have a task formulated like this
Please print a matrix in spiral order, clockwise from outer rings to inner rings.
I decided to implement it in Clojure.
(def matrix '((1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16)))
(def big-matrix '(
( 1 2 3 4 5 6 7 8 9 )
( 32 33 34 35 36 37 38 39 10 )
( 31... |
I have coded this static method for converting a double matrix into a nifty String.
It considers the width of the matrix to be equal to the length of the longest row. Now, if some matrix entries are considered missing, strings of the format x.xx.. are added instead of them to the overall string.
Also, rows that are emp... |
I recently read and answered Martin R's Recursive flattening of Swift sequences and continued to play around with the code until I arrived at something that was both pretty cool and possibly an abomination. So I figured I'd come back to CR with it and ask others' opinions.
If you want a full context, you should refer t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.