instruction stringlengths 71 71.9k |
|---|
Is there any legroom left for optimization (without switching to C)?
static byte[] generateSound(double frequency, int sampleRate, int samples) {
byte output[] = new byte[2 * samples];
int idx = 0;
double _tone = 2 * Math.PI / (sampleRate / frequency);
for (int i = 0; i < samples; ++i) {
doub... |
Is the following procedure good for shuffling data in general (not just for JavaScript)?
function Shuffle(array) {
var temp = null,
len = array.length - 1,
rnd = null;
for (var i = len; i > 0; i--) {
// Generate a random number in which does not exceeds the length of array.
rnd = Math.floor(Math.r... |
I've made a program to find the missing element (if there's one) in a sequential list:
Program criteria:
Returns -1 if a list is sequential, otherwise the missing element in a non-sequential list is returned.
To perform binary search, we need a key to half the problem size. Here the key is to find the distance between... |
I am implementing finite field arithmetic for some research purposes in C++. The field of order v, when a prime (and not a prime power), is just modular arithmetic modulo v. Otherwise, v could be a prime power, where the arithmetic is not straightforward. For simplicity, assume that files that contain the multiplicatio... |
I've made code that scores each letter in a word you input according to the table below:
1: AEILNORSTU
2: DG
3: BCMP
4: FHVWY
5: K
8: JX
10: QZ
I appreciate any feedback, but the main reason of this post concerns the charPoint method. Should I rewrite this using switch? Or is there an even better way to... |
Any thoughts?
print('*'*44+'\n****How Many Seconds Have You Been Alive****\n'+'*'*44)
while True:
try:
print('\n--------------------------------------------')
Age = int(input('\nHow old are you?: '))
if Age<1 or Age>90:
print('(Input Error)*Enter Valid Age*')
contin... |
Inspired by this question I wrote a memoized form of the collatz sequence calculator.
The idea was to cache the sequence lengths for as many sequences as possible, from 0 to some value. I managed to (on my PC) get that value up to 1427500000, which is a large number.
I ran this particular calculator and it eventually c... |
Is this an efficient way to compute the value of Pi, where the limit of j \$\propto\$ accuracy?
PI = 0;
for (var j = 1; j < 100; j+=2) PI += (4/j)*((j+1)%4?1:-1);
The formula I used to write this is:
$$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$
|
How can I make my code better?
function generateRandNum(min, max) {
minimum = Math.ceil(min);
maximum = Math.floor(max);
return Math.floor(Math.random() * (maximum - minimum)) + minimum;
}
function generateNewPost(json_data) {
var rand_num = generateRandNum(0, json_data.length);
console.log("gener... |
I was trying to write some simple data structures to practice ownership concepts in Rust:
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
struct List<T> {
head: Link<T>,
}
pub struct Iter<'a, T: 'a> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
pub fn new() -> ... |
Here is my code for this problem. Any bugs, performance in terms of algorithm time complexity, code style advice are appreciated.
This is a continued discussion from (Find smallest subset prefixes) and since it is new code, I post a new thread.
Problem:
Given a set of strings, return the smallest subset that contains ... |
Online challenge on Hacker Rank.
Problem Description
Alice wrote a sequence of words in CamelCase as a string of letters, S ,
having the following properties:
It is a concatenation of one or more words consisting of English
letters. All letters in the first word are lowercase. For each of the
subsequent words, t... |
Problem statement
Given an array S of n integers, are there elements a, b, c
in S such that a + b + c = 0? Find all unique triplets in the
array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], a solution set
is:
[
[-1,... |
Online challenge on Hacker Rank.
Problem Statement
Steve has a string, S, consisting of n lowercase English alphabetic >letters. In one operation, he can delete any pair of adjacent letters with same >value. For example, string "aabcc" would become either "aab" or "bcc" >after operation.
Steve wants to reduce as much... |
Problem statement
Professor GukiZ has hobby — constructing different arrays. His best
student, Nenad, gave him the following task that he just can't manage
to solve:
Construct an \$n\$-element array, \$A\$, where the sum of all elements
is equal to \$s\$ and the sum of absolute differences between each
pair of... |
This is my second attempt to create a strongly typed builder for the Dependency Property. I've improved the two main weaknesses of the previous version which were:
Can specify only PropertyMatadata but not FrameworkPropertyMetadata
Can coerce value but not cancel the operation with DependencyProperty.UnsetValue
The ... |
Please review my code for printing a Christmas Tree.
The idea was to merge some functional programming ideas (immutability, streams) and OOP (every thing is a small object).
I'm looking for a review focused on readability of the code.
Here is a output from the code:
*
***
*****
*******
*********
An... |
The challenge
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1,2,...,n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.
Input
\$n\quad (0 \lt n \le 16)\$
Output
The output format i... |
My code works as expected but I am not sure how to optimize the code. The purpose of the code is to find files with given parameters and copy them to a separate folder.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import javax.swing.JOptionPane;
import java.io.File;
import ja... |
I am trying to keep the progression of the Review Queue Notifier moving forward. My next big move is to turn it into an extension for Chrome and FireFox and eventually Edge.
I would like the Javascript for the code reviewed again to get me back into the groove of coding this extension/script.
Here are the guts:
$( doc... |
Online challenge on Hacker Rank.
The king has a string composed of lowercase English letters. Help him
figure out whether any anagram of the string can be a palindrome or
not.
Input Format
A single line which contains the input string.
Constraints
1 <= length of string <= 10^5
Each character of the string is a lo... |
Previous version is here. Sources are available on GitHub.
I am trying to define a plug and play CQRS architecture which leverages stereotypical role implementations (Validator, Reader, Writer, Logger, Query, etc) by automatically instantiating associated services through a very limited use of Service Locator.
Demo cod... |
I created a view called PullView which adds a level of interactivity to UI components. PullViews can be pulled sort of like a rubber-band and bounce a little when released. The code for it is fairly simple.
I would like comments on how to improve code structure, performance, etc. if possible.
import Foundation
import ... |
Most properties have simple requirements so it should be possible to register their Dependency Property fields declaratively.
I made a small experiment and it seems to work just fine. The first attempt supports DefaultValue and Validation attributes.
It looks a little bit like JavaScript ;-)
The new DependencyPropert... |
I was reviewing for an interview and encountered the following question (and I'm paraphrasing):
Suppose you're given a shuffled array of numbers containing all of the numbers between a min and a max, inclusive, with one number missing. For example, for an array of size 5, you could have something like 2, 5, 4, 1 (wher... |
I've written this implementation of a binary search algorithm, and wanted to know if it was efficient and where I can improve.
function search(el, list) {
// list = list || LIST;
var LIM = Math.ceil(Math.log2(list.length)),
lb = 0,
ub = list.length - 1,
i;
while (el !== list[i = ~~((... |
I'm trying to make a simple app in C# that gets the weather data from http://openweathermap.org/api (OWM).
Here attached are two classes that I use to initialize WeatherData for selected City and to download and parse XML data from OWM API. I would like to know your opinion on the structure of the classes and the way I... |
The next post in my Checker series: The C# wrapper for my F# library to make it cleaner for these methods to be called from C# code.
GeneralTypes.cs
public enum Player
{
White, Black
}
public enum PieceType
{
Checker,
King
}
public static class Extensions
{
public static Player Convert(this Checkers.T... |
I put together a script which goes through all of the files in Google Drive, and writes a spreadsheet with all of the files with their name, containing folder, URL, and date last updated.
function Start_Up() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
shee... |
(...as I learn Kotlin) I want to get the indices of the two numbers such that they add up to a specific target from a given array of integers.
Solution:
fun sum(values: Array<Int>, result: Int): Array<Int> {
for ((i, e1) in values.withIndex()) {
for ((j, e2) in values.drop(i + 1).withIndex()) { // ...or: values.d... |
I have the following code which iterates through some divs of an array to show() them. I was wondering if there is any way to rewrite the for loop using filter(). Will this have a better performance over my initial code?
var selectEnabledGenerators = function(generators) {
//List of generator indexes to show
va... |
This is based on a programming challenge I recently solved. However, since the writer of the challenge asked me not to disclose the question and/or it's answer, I modified it a little. If it doesn't make sense: my mistake.
The target is to find all numbers in a file and sum those. So if the following is found:
Sed ut ... |
I'd like to get a code review and some insights of whether I chose a good way to do this. What would other, clever ways look like.
"""
Convert numeric string to number withoutusing python's built in functions.
"""
dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4... |
I'm working on the problem of finding 2 numbers that their sum is closest to a specific number. Input numbers are not sorted.
My major idea is to sort the numbers and find from two ends. I'm wondering if there are any better ideas in terms of algorithm time complexity. Any advice of code bug and code style is appreciat... |
You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child n... |
Online challenge on Hacker Rank.
Alice has a binary string, B, of length n. She thinks a binary
string is beautiful if and only if it doesn't contain the substring
010.
In one step, Alice can change a 0 to 1 a (or vice-versa). Count
and print the minimum number of steps needed to make Alice see the
string as ... |
This is my first Angular2 component, which makes two api calls: the first call provide the input for the the second one.
The following is my attempt at this code.
@Component({
selector: 'result-panel',
templateUrl: 'panel.component.html',
styleUrls: ['panel.component.css'],
providers:[FindIpZo... |
I have an assignment to implement realloc in C, This's my code please review it.
void *my_realloc(void *ptr, size_t len)
{
void *real;
real = malloc(len);
memset(real, 0, len);
if (real)
memcpy(real, ptr, len);
free(ptr);
return (real);
}
|
Online challenge on Hacker Rank.
Shashank likes strings in which consecutive characters are different.
For example, he likes ABABA, while he doesn't like ABAA. Given a
string containing characters A and B only, he wants to change it
into a string he likes. To do this, he is allowed to delete the
characters in ... |
I am working on designing tables for work orders.
The problem:
There is different work order models (from now on called WOM)
The WOMs share some attributes (Num, Date, Description, ... etc)
The WOMs have details such as:
Sectors on wich the work is done.
Some WOMs use storage tank instead of sectors (products are pr... |
I have written this Ruby script to download some file from server using SFTP. Help me improve this one.
Find the original script at this link
#This script is used to download file from the server to your local machine
#The implementation is based on pure Ruby implementation of SFTP using gem Net SFTP
#To install this o... |
Objective
Write a function JoinWithAnd in Java with the following signature:
String JoinWithAnd(String a, String b, String c, String d, String e)
So that:
If no input is provided, it returns an empty string
If any one input is provided, it returns the string as it is
If more than one inputs are provided, it combines... |
I'm working on socket programming in C. I have no problem with usage the threads. This all works fine but I'm new in this area. I wrote this code in client.c but is there any misused code or something may cause problems in the future?
My client sends a message to the server and client can receive it. There are 2 major ... |
I have written a simple C header for converting the endianness of short integers and long integers. It uses the GCC macro __BYTE_ORDER__ to check the system's byte order and define the macros based on that.
The header creates the macros LITTLE_ENDIAN_SHORT(n), LITTLE_ENDIAN_LONG(n), BIG_ENDIAN_SHORT(n), BIG_ENDIAN_LONG... |
I am looking for some advice to this code I made, which enables a fellow programmer to create his own AI for Connect Four whilst not really having to code the game itself.
Match class
public sealed class Match
{
public const int cWidth = 7;
public const int cHeight = 6;
private static Random Random = new Ra... |
I've got this little module that returns basic user data required for a web app that's extracted from a large number of columns per row. I was asked to replace the small, column specific select statement I'd prepared with a stored procedure that returns the entire row. This moves column pruning into the server.
I've m... |
This code replaces every vowel of the string with "X":
def vowel_censor(sentence)
vowels = "aeiou".chars
result = []
sentence.chars.each do |charachter|
if vowels.include?(charachter)
result << "X"
else
result << charachter
end
end
result.join("")
end
puts "------... |
I wrote this program as a start towards implementing the game Scattergories. I had a problem with the _sleep command so I used Sleep in the windows.h library.
Eventually, I would like to add a way to either check if a word is correct, or to suggest words, and to activate a sound when the timer is done.
// A program to... |
After doing a simple coding challenge regarding strings, I realized that I have forgotten a few things about them. As such, I decided to do a few basic string manipulation practices for myself.
One of them, which I found in my old Java assignments, was a word guessing game. Very small, nothing special. As such, I decid... |
I want a flexible and fast way to break a string up into strongly typed tokens so that I can do things like the following:
let sampleText = "~~~hello12.34\n\n100,000.00~~~world~~~"
let tokens = Tokenizer<NumberOrWord>.tokens(from: sampleText)
// tokens => (pseudo output)
// [(word 'hello' at range 3, 8),
// (numbe... |
I've made an object builder which can create all sorts of classes, it can also create immutable objects.
There are 2 requirements that must be met in order for this pattern to work with fully immutable objects.
The properties that you want to be modified must have a backing readonly field.
The backing field must follo... |
Considering that two bitsets are provided in the form of strings, char a[] and char b[], as in the code below. And the task of add that bitsets is given. I take it and wrote the following to sum the two bitsets:
#include <stdio.h>
#include <string.h>
int carry = 0;
char result(char r, int c) {
char R = '0';
if... |
I have this expression:
public static readonly Expression<Func<ApplicationUser, decimal>> EfficiencyPercentExpr = e =>
(e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30)).Count(x => x.Status != Order.OrderStatus.Deleted) > 0)
?
(
e.ExecutorOrd... |
The following text is from Hal Daumé III's "A Course in Machine Learning" online text book (Page-41).
I implemented the following:
Is the implementation correct?
D = 2;
MaxIter = 100;
w = zeros(1, D);
b = 1;
for i=1:MaxIter
output = zeros(D,1);
for j=1:D
a = activ_func(product(x(j,:... |
I am tasked with being able to find the \$n\$th prime number. I've tried to implement something like the sieve of Eratosthenes in increments of 200. The code works and returns the \$n\$th prime number. However, when asking for the 1000th prime number I already notice a significant lag on my box.
This code needs to be a... |
I began creating and refining my resume in LaTeX a long time ago. I recently modified it such that I would feel comfortable putting it out there for others to use as a template, if they wish.
It has the unfortunate quality that when I begin modifying it, I have to tweak the white-space quite a lot if I wish to keep it ... |
I am working on learning how to do frequency analysis of Server Fault question tags to see if there is any useful data that I can glean from them. I'm storing the raw data in Bitbucket for global access, so this code will use the same dataset I am using, it's about 30Mb.
import pandas as pd
debiandf = pd.read_csv("htt... |
I was making a library program for trying to practice C++. I wanted to use a vector to store all the books, the books being a struct to hold the general things the books would have.
struct Book
{
string bookName; // book's name
string bookAuthor; // book's author
string bookID; // a random generated stri... |
I am making a flashlight plugin for macOS.
Here is the main code, plugin.py, the method results gets called first and is passed a dictionary like this for example:
{ "~arguments": "3h30m" }
And I try to parse the time span given and activate a macOS alert later.
Anyway, I'd appreciate any pointers at all, I'm pretty n... |
Given a decimal number I need to convert it into binary
Given a binary number I need to convert it into decimal
After the conversion I need to perform some operation on it (for example, addition). I also need to print the result with a specified width.
Binary-Decimal:
n1 = int(input("Enter a binary number: "))
n2 = i... |
I'm working through Advent of Code 2016 in Rust. The prizes go to the swift, but I'm aiming for well-written code. This is Day 1.
To summarize the problem statement, given a instruction string of turns and distances (e.g. "R5, L5, R5, R3"), return the Manhattan distance from the origin (in this case 12).
I am using Rus... |
I have been trying to implement the Bill Pugh Singleton Design Pattern using a private static class to return the singleton retrofit instance. So far I have been able to come up with the following code. Can someone help me review this code and confirm if this is a proper implementation of the singleton design pattern s... |
This is a follow up of the question I posted previously here.
I made some changes, based in the answer by MikeMB, making use of asynchronous calls (with std::async and std::future), instead of std::thread as before.
monte_carlo_pi.cpp:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstdint>
#includ... |
I'm looking for suggestions on how to improve the usage of modern C++ features with this simple graph search algorithm, particularly with regard to the use of STL containers and lambda expressions.
Note: I am using an implementation of BFS that can be obtained from DFS by replacing the stack with a queue.
#include <deq... |
Numeros, the Artist, had two lists A and B, such that B was a
permutation of A. Numeros was very proud of these lists.
Unfortunately, while transporting them from one exhibition to another,
some numbers were left out of A. Can you find the missing numbers?
Notes
If a number occurs multiple times in the lists, yo... |
Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they
pool together m dollars for ice cream. On any given day, the parlor
offers a line of n flavors. Each flavor, i, is numbered
sequentially with a unique ID number from 1 to n and has a cost, ,
associated with it.
Given the value of m and the co... |
The goal is to pick items from a listview, do some web related task with the information and then update the UI with the returned information from the web request.
The problem is with having multiple list view items processed at once, me being a newbie to C#, i came up with this code, I'm pretty sure this is not good, ... |
I got the idea for this program from this site.
functions.cpp:
#include <iostream>
#include <cstdlib>
#include <iomanip>
namespace my
{
int getOneOrZero()
{
return (rand() >> 14); // >> the bitwise operator
}
// getArray leaves the numbers ( 0-99 ) that have in their bit position represented by b... |
I am rotating images inside some divs.
An image is associated with a link.Eg: image0 is associated with link0, image1 with link1 and so on.
image0 and link0 should display in pos-1
image1/link1 and image2/link2 should rotate on page refresh in pos-2
image3/link3 and image4/link4 should rotate on page refresh in pos-... |
I am using a DataTable and the MySqlAdapater to insert around 100 000 rows with around 40 columns to a MySQL database.
I chose this way, because my program needs run on mono (unix / mac) where I could not establish a connection to my database via the System.Data.Sql package, but only via the .NET connector Mysql.Data.M... |
I have a model named User. Each user can have some social links. Now I want to get all users with their social link as a single row in the result. Here are my models:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<SocialLink> SocialLinks { get; set; }
}
... |
I've written a basic implementation of a singly linked list in Scala. I would appreciate any feedback and improvements (especially the remove() method, I feel like it could be implemented better).
Node class
class Node[T](data: T, var next: Option[Node[T]] = None) {
override def toString: String = data.toString
}
Si... |
A local university's graduate school has a field placement that's a required component for graduation. Each student works in the field (something like a residency for medical students) for one year in addition to completing their course work.
The process of matching students with placement locations is called the matc... |
Over the weekend I decided to start work on my own version of FastMember. I began with my take on an implementation of TypeAccessor so that I could work with the properties of any type, create an instance of the type, and one or two other little tricks. I've reached a point where I'm out of ideas on how to improve the ... |
A simple selection sort functions in R. Just for practice.
Given the choice of algorithm and tools I wonder what can most easily be improved about the functions.
NB. I wanted to keep the first function as elemental as possible.
# Selection sort playing with loops
sels <- function(x) {
n <- length(x)
for (i in 1:(n... |
I'm working through Advent of Code 2016 in Rust. The prizes go to the swift, but I'm aiming for well-written code. This is Day 2.
To summarize the problem statement, given a newline-separated list of directions (e.g. "ULL\nRRDDD\nLURDL\nUUUUD\n"), move about on a 9-key keypad starting at 5, freely colliding with the ed... |
So I got bored and made a simple noughts and crosses game with colours instead of symbols.
The colours are red and blue and I made the GUI in NetBeans with my own code in combination with the NetBeans GUI Editor.
My Code:
package com.coal;
import java.util.Random;
public class Noughts extends javax.swing.JFrame {
... |
I'm new to swift and I want to know if I'm doing something wrong or a harder way. I made a simple war game app. Tames of variables aren't correct, I know, but I was doing it quickly and I didn't worry about names of variables in that small project so I named them in English with Polish grammar.
import UIKit
class View... |
I created a TileMap-class to load tile sets, create and display tile maps. It is far from perfect so I want your opinions on how to improve it!
How it works:
Create TileMap object with "new TileMap( int tilesize )".
Create a tile set with "createSet( String path )" and specify the tile types with "setTileSet( int row... |
Here is my Field Can Be Made Readonly analyzer and quick fix. I would appreciate tips on how to improve my code, and on missed test cases.
First, the rules it works with:
It will only fire on private fields to make things simpler (fields in other scopes should be properties, anyway).
If the field is only assigned inl... |
I wrote a simple logger for a server I'm writing. I'm wondering if anyone has any suggestions to improve it.
doom_logger.erl
-module(doom_logger).
-author('Andrew McRobb <andrewmcrobb@gmail.com>').
-include("include/log_types.hrl").
-export([start/1, start/0, terminate/1, log/4, log/3]).
-record(logger_state, {
... |
I've recently answered a question here, where the goal is to mimic some functions from System.Reflection in order to avoid it's direct usage as much as possible, because it works slow.
Currently available features are :
Cloning properties from one instance to another.
Setting properties of instances.
Getting property ... |
The following code simulates a game of signals in which four participants (playing in pairs) show (muestra) and see (observan) signals. Signals are randomly assigned in the first round. Signals in the second round are assigned depending on a probability equation that takes into account memory dictionaries.
The final ou... |
As part of a game engine I am creating, I am in the process of writing a bunch of math classes (vector2/3/4, matrix2/3/4, and quaternions to start with).
Vec2 class:
import math
import random
class Vec2(object):
def __init__(self, x, y):
self._x = float(x)
self._y = float(y)
@property
def ... |
I'm working on this problem,
Problem statement,
Given a Binary Tree, find vertical sum of the nodes that are in same vertical line. Print all sums through different vertical lines.
Examples:
1
/ \
2 3
/ \ / \
4 5 6 7
The tree has 5 vertical lines
Vertical-Line-1 has only one node 4 => vert... |
This is my attempt to implement the style of coroutines I described in my answer to Small coroutine class. What do you think of it?
(My unusual dialect is due to my compiling with -std=c++1z on a moderately recent Xcode. It doesn't support std::apply or if constexpr or std::is_same_v, but it does support fold-expressio... |
We started programming in school this year. I wasn't expecting to learn much but the pace is really slow so I tried to learn some things myself. I decided to do a little project for a start and that is a simple snake game. I would like to know what I am doing bad ( I know about the lack of consistency in naming ) or if... |
I'm basically trying to build a function that searches all nodes on the DOM to check for data attributes, then swap them out with whatever is stored with the "data-intl-" attribute. For example, if someone had data-intl-attr, whatever attr is on, that node would get replaced by what's in data-intl-attr.
The code works... |
I couldn't find a .NET date format type to handle dates in format I need to process, they sometimes have time zone offset with +/- prefix followed by 3 digits for the number of minutes timezone is offset by. i.e. +11:00 is written as +660
Usage Example:
GetDateTime("20161124181215.000000+660")
The function:
private Da... |
I'm working on a program that updates the background of an x11 desktop at a specified interval. However, it eats large amounts of my CPU just sitting idle. I know this is due to the main loop running faster than I want it to. I've used a couple shameful hacks to quell usage down to about 15% but now I am searching for ... |
I'm doing this HackerRank problem which basically boils down to what I've written in the title. We have to find out the distance between all the odd values in the array. I've written this code below which passes all the test cases but I think I can do better, namely, I don't have to make a separate array (oddindices) t... |
After some investigation, I implemented an asynchronous TCP server as per the following example. During my investigation I was unable to find an example that cleanly shuts down the server; after some experimenting I was able to furnish my code with this functionality. I would appreciate a review of the service code for... |
Given a string S, find the number of "unordered anagrammatic pairs"
of substrings.
Input Format
First line contains T, the number of testcases. Each testcase
consists of string S in one line.
Output Format
For each testcase, print the required answer in one line.
Sample Input#00
2
abba
abcd
Sample Output#00
4
0
... |
I have this helper method that generates an HTML calendar based on the current day:
module PageHelper
def calendar(date)
cal = "<table class='table-condensed table-bordered table-striped'><thead><tr>"
days = %w(Sun Mon Tue Wed Thu Fri Sat)
days.each do |day|
cal += "<th>#{day}</th>"
end
cal+... |
This is the code I currently have to get all neighbors of any given element in a matrix like structure:
struct Coordinates: IEquatable<Coordinates>
{
public int Row { get; }
public int Column { get; }
public Coordinates(int row, int column)
{
Row = row;
Column = column;
}
publi... |
Scenario:
Check if the user exists
If yes: update the details
Else: insert the user details
public bool AddUsers(IEnumerable<UserDetail> users)
{
using (var dbTransaction = System.Data.Entity.Database.DefaultConnectionFactory.CreateConnection("MyCon").BeginTransaction())
{
using (v... |
I'm a .NET (C#/VB) developer who knows a little C and happens to need to write a native C++ Windows DLL.
Please have a look at the following code and tell me if the string operations are idiomatic C++:
int dpi;
void __stdcall FooEntryPoint(ENTRY_INFO* inEntryInfo)
{
dpi = *reinterpret_cast<int *>(inEntryInfo->User... |
Background
A VSCode extension that uses Chance.JS to generate random data types.
Concerns
My main concern is that there are 4 levels of function references that feels like a hack. From registerCommand → insertFunc* → randomFunc* → processSelection.
If the code is sensible TypeScript/JavaScript
The Code
export functi... |
I've been developing this application as my first C++ project and am at a point where it is functional and would like to take a step back and critique/improve my code from a standpoint of manageability and better coding practices. Additionally, it has some stability issues which I need to address, so I thought instead... |
I am making a text snipper plugin for WordPress. Basically, I want it to truncate multiline text that overflows the height of its container and add "...". My code works for direct child elements, too. It is also responsive and keeps working based on window resize.
However, I'm worried that my method might be too much o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.