Click here to Skip to main content
15,897,273 members
Everything / Code challenge

Code challenge

code-challenge

Great Reads

by Thomas Daniels
This article is a solution to CodeProject's Weekly Challenge: "A knight on a chess board".
by Kornfeld Eliyahu Peter
Think algorithm...

Latest Articles

by Thomas Daniels
This article is a solution to CodeProject's Weekly Challenge: "A knight on a chess board".
by Kornfeld Eliyahu Peter
Think algorithm...

All Articles

Sort by Score

Code challenge 

22 Feb 2023 by Chris Maunder
Today's challenge is provided by Jeroen Landheer.Write a program that lets a knight hop over a chessboard so it touches all squares, but that knight may never use the same spot twice. Starting position should be given by the user (or provided as a random location if you don't feel like...
12 Jan 2017 by Chris Maunder
Today's challenge is a simple one: given an arbitrary set of points in the x,y plane, determine the centre and radius of the smallest circle that will enclose all points. The circle may intersect points in the set.Bonus points awarded for the use of an interesting language. Or an interesting...
11 Mar 2017 by Thomas Daniels
That was fun! My code and answer were growing really big, here's an article instead:Knight's tour on a square chess board: coding challenge[^]As a bonus, it can also draw a picture or animated GIF of the knight path :)
6 Dec 2016 by Chris Maunder
Your coding challenge of the week is a simple one. Or so it seems.Given a text string, convert the tabs to spaces. Assuming tab markers are 4 characters apart[ ][ ][tab]Hello, world!becomes[ ][ ][ ][ ]Hello, World!Where [ ] = space character, [tab] = tab character (I chose to...
2 Mar 2017 by Chris Maunder
Given a stream of floating point data that may never end (think of a politician's speech converted to binary and cast to 4 byte floats), calculate a rolling average and standard deviation. Some background on this can be found at Efficient and accurate rolling standard deviation – The Mindful...
13 Jan 2017 by Graeme_Grant
Solution 5 was my first attempt at this problem and the test points (more than posted) used reflected that the solution worked. So I converted to several different languages, partially as a learning curve and a challenge for myself. Happy with my efforts above I shared the code and...
19 Jan 2017 by Chris Maunder
The challenge for this week is, as always, a simple one. Given a 64 bit integer create a method that will convert the value to it's spoken equivalent. For example: 1,203 would result in "One thousand, two hundred and three"The scope of making this needlessly convoluted is high. Go at...
30 Mar 2018 by Chris Maunder
Today's coding challenge is pretty loose in terms of how you approach it and how you interpret the problem.Given a collection of items (integers, strings, objects - whatever) determine the set of subitems in that collection that are repeated.For example{1,2,3,3,4,5,5,6} =>...
18 Jun 2018 by Chris Maunder
Today's challenge is back to strings.Given a random (or not so random) string, generate unique anagrams.Bonus points: Hook into a spell checking service of your choice (local machine, backed into the OS, remote webservice) to only return anagrams that are actual words.The trick: it...
21 Apr 2020 by Maciej Los
Why to force doors wide open? Take a look here: Substring in Java - javatpoint[^] public class TestSubstring{ public static void main(String args[]){ String s="SachinTendulkar"; ...
15 Mar 2017 by Graeme_Grant
Here is a solution using an interpretation of Warnsdorff’s Algorithm: Knight's tour - Wikipedia[^]Update: the code was refactored without sacrificing performance.ObjectiveFlexible core with the following goals:1. Reuse in other board-orientated puzzles like: Eight queens puzzle -...
25 Nov 2016 by Richard Deeming
Yay! A chance to use Regular Expressions without summoning the elder gods! :)Start with a structure to convert a string to a bad word, taking the "bonus points" rules into account:public struct BadWord{ public BadWord(string word) { if (string.IsNullOrWhiteSpace(word))...
27 Nov 2016 by Peter Leow
I was reading up on Python online, then chanced upon this pooping oops I mean coding challenge, thought why not try this out on Python. Here it is fresh from the loo oops again I mean oven."""poop.pyby Peter Leow the pooper"""import redef functionStartWithPoop(m): ...
28 Nov 2016 by DarrenWheatley
Not sure if my Excel VBA solution posted, so I'm trying againPublic Function noBad(ByVal badstr As String) As String Dim badWords As Variant, goodWords As Variant Dim i As Integer, bw As String badWords = Array("poop*", "PHB", "gotten", "POOP*") goodWords = Array("p**p",...
1 Dec 2016 by Thomas Daniels
BrainfuckWell, that was fun :)>,[>+++++++++->+[>-------------------------------->-------------------------------->]>>,]To run this, paste the code in this online interpreter[^],...
2 Dec 2016 by H2O-au
Thought I'd give this a go, but alas my solution seems too sensible for this challenge... :DUsing C# enumerables and yield...public static partial class Extensions{ public static string ToTabified(this string input, int markerSpacing = 4) { return new...
13 Dec 2016 by CPallini
This is the algorithm of solution 2, improved by means of PIEBALD's suggestions, and ported to C# in order to simplify the comparison with other algorithms.In my humble opinion ( :-D ) it is remarkably fast.static uint gcd(uint[] a){ uint iom = 0; uint min; uint i; uint len...
20 Dec 2016 by Chris Maunder
Today's challenge is late but simple one.Given a set of (x,y) points representing a polygon, determine whether a given (x,y) point is inside or outside the polygon. For example, the polygon defined by the points (counter-clockwise) { (2,0), (4,1), (4,4), (2,5), (1,2) and (2,0) } contains...
6 Jan 2017 by Kornfeld Eliyahu Peter
For JSOP only :-)IDENTIFICATION DIVISION. PROGRAM-ID. CPCC4-POINT-IN-POLYGON.DATA DIVISION. WORKING-STORAGE SECTION. 01 T1 PIC S9(6) VALUE ZERO. 01 T2 PIC S9(6) VALUE ZERO. 01 T3 PIC S9(6) VALUE ZERO. 01 T4 PIC S9(6) VALUE ZERO. ...
20 Dec 2016 by Jon McKee
First, I'd like to explain my methodology. Second, I'll explain my code.So first, my technique is similar to the ray-casting algorithm. I double cast a ray in both directions and count the intersections individually then OR them together which allows me to catch points on sides like...
11 Jan 2017 by Peter Leow
I was late because I was misinformed that the Quote:... challenge is a simple one:Nevertheless, I took a second look, suddenly these stuff started haunting me, geometry, linear algebra, slope, y-intercept, and whatnot. Look that the only way to free myself from the nightmare is to take on this...
11 Jan 2017 by Kornfeld Eliyahu Peter
Maybe a bit late to the party, but I worked hard...Coding Challenge: Smallest Circle Problem[^]
16 Jan 2017 by Graeme_Grant
You didn't specify the range of ints to be tested or the Scale Mode[^]. Back in my days of school, a billion[^] was not the same as some other parts of the world however luckily, the world is using the US standard.So here is my version that supports both positive/negative ints from Int16...
7 Mar 2017 by Jörgen Andersson
Inspired by Solution 2 but considerably faster class Program { private static IEnumerable GetWords() { //using a local version of: //https://raw.githubusercontent.com/dwyl/english-words/master/words.txt using...
11 Apr 2017 by Patrice T
I think I got my solution (finally): I used again my beloved Clipper language (FoxPro alike). - First I use the list of numbers like a circular buffer: data don't move, pointers are. - Then I build a helper array with final position in sorted array, so I don't make assumption on data:...
3 May 2017 by Chris Maunder
Given a string of numbers insert any of the operators +.-./.*, % or ^ between whichever digits you wish so that the equation evaluates to the given number. eg Use 1234567890 to create an equation that equals 100. Answer: 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 - 0 = 100 Your solution should be general...
5 Dec 2022 by OriginalGriff
Quote: The below code is what I have tried but it's entirely wrong! Yes. It is. And you don't know why. Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your...
9 Nov 2023 by Richard MacCutchan
You need to show the code you have written, and explain exactly what help you need. But if you are expecting someone here to write the complete assignment for you, I am afraid you will be disappointed. This site is here to provide help, not to do...
26 Nov 2016 by Jon McKee
Not sure on the rules, just wanted to add this for fun. I love code challenges.This solution, in contrast to my other one, reduces the number of strings nuked during processing. It also uses only a single Regex call to process all bad words. Even though I construct an additional...
28 Nov 2016 by Andrei Bozantan
Actually, stating that this challenge is easy is misleading. Handling text is never easy, if you want to work with Unicode. Here is a my take on it.using System;using System.Collections.Generic;using System.Globalization;using System.Linq;using System.Text;class WordFilter{ ...
1 Dec 2016 by Robert g Blair
COBOL has awesome string handling:identification division.program-id. FixBadWords.data division. working-storage section. 01 wsData. 03 wsComment occurs 5 times pic a(255). 01 i pic 9(1).procedure division. move "My PHBis such a poophead. It's...
1 Dec 2016 by David O'Neil
EDIT:* Figured out way to make 'poopoopoop' become 'p**p**p**p' (without recursion) and keep other design constraints.* Figured out an 'Oh Duh - that's so simple!' way to keep 'nincompoop' as 'nincompoop' - just replace it with itself!* Made class static, which resulted in about 8%...
1 Dec 2016 by losvce
Maybe I took things too literally.using System;using System.Collections.Generic;using System.Linq;namespace Test{ public class TabConversion { public static void Main(string[] args) { string literalTest1 = "[ ][ ][tab]Hello,...
10 Dec 2016 by H2O-au
Caching prime factorsWhat strikes me as interesting about this problem is the low value of nmax = 10,000.* There are only 1,229 prime numbers less than 10,000 (the largest of which is 9,973)* All integers less than 10,000 have at most 13 prime factors (since 214 = 16,384 > 10,000)So...
10 Dec 2016 by PIEBALDconsult
I do have implementations of GCD using the Euclid and binary algorithms -- for two operands only -- but I chose not to use them.So here's a simple (sophomoric perhaps) method that will reduce the values in the List and return the GCD.It works for negative values, zeroes, and single-item...
13 Dec 2016 by Maciej Los
Well... Many of you knows that i'm a fan of Linq solutions!//given listint[] givenlist = new int[]{247, 8645, 1216, 3648};//int[] givenlist = new int[]{5, 12, 316, 648}; //gcd: 1//get the list of divisors from 1 to min of given list//gcd cannot be greater then min of given...
14 Dec 2016 by Kornfeld Eliyahu Peter
Finally I got to finish the 6502 assembly solution... I used a C64 emulator as a host for the code, so beside the actual computation, there are some lines to print the result out too...The most interesting thing are, that not only 6502 is a 8 bit CPU (so not 16 bit arithmetic), but it has no...
16 Dec 2016 by Ramza360
Adding another example using most of what OriginalGriff wrote except no foreach loop.public class TestPoints { GraphicsPath path; public TestPoints(Point[] points) { path = new GraphicsPath(points); } public bool CheckVisible(int x, int y) { ...
16 Dec 2016 by Thomas Daniels
Time for some maths! My code uses the ray casting algorithm: it looks at how many times a ray, starting from the given point to whatever direction, intersects with the polygon. If this number is odd, the point is inside the polygon. If it's even, the number is outside the polygon./*...
16 Dec 2016 by Marc Clifton
If you allow me an extension method so I can get fluent coding: public static class GPExt { public static GraphicsPath AddPolygon2(this GraphicsPath gp, PointF[] points) { gp.AddPolygon(points); return gp; } }I can...
5 Jan 2017 by Peter Leow
Picked out this new mission while waiting for my flight home. One look and this is going to involve geometry, that means Cartesian coordinate system, vectors, edges, and angles sort of things. To kill time, I started drawing out my thought on the phone... There are three ways to solve this...
9 Jan 2017 by JohnLBevan
A really basic PowerShell solution: $Coords = @( @(100,50) ,@(50,50) ,@(10,30) ,@(100,30) ,@(102,90) ,@(80,60) ,@(40,110) ) $center = $Coords | %{ $a = $_ $Coords | %{ $b = $_ ...
10 Jan 2017 by Vladislav Kulikov
Depending on the data the 'solution' circle will be defined either bya) two points (these two points define circle diameter) [^] b) OR three points (these three points are on the 'solution' circle) [^] That's said we may do the following:1) find two most distant points, consider them...
15 Jan 2017 by Patrice T
My solution with a real program. Clipper language (mostly FoxPro)The method:1) find the farthest 2 points from each others.2) try the 2 points on circle solution, center is in the middle of the 2 points.3) if a point a farther than the radius, the 2 points solution don't work.4) switch...
13 Jan 2017 by Mehdi Gholam
Really!? you should know how to use your own site by now! :)using System;using System.Speech.Synthesis;namespace SampleSynthesis{ class Program { static void Main(string[] args) { // Initialize a new instance of the SpeechSynthesizer. ...
23 Jan 2017 by Chris Maunder
The late coding challenge for today is straightforward.Given a set of integers, arrange the integers so that the final integer thus formed is the largest number possible.For example.{ 1,5,67,9 } would be arranged to form 96751The list may contain up to 50 numbers, and each number...
22 Jan 2017 by PIEBALDconsult
System.Console.WriteLine ( BiggestIntegerInator( System.Environment.CommandLine.Rive ( Option.RemoveEmptyEntries | Option.RemoveQuotes | Option.HonorEscapes | Option.HonorQuotes )) ) ;(Rive is in one of my Articles, it's a more flexible version of Split.)1...
5 Feb 2017 by Chris Maunder
Yes, the classic LCS problem. Given two or more strings find the longest common substring in each string.One caveat: No C#, C, C++, Javascript or any C-based programming language[^], nor any VB-based language (VB, VB.NET, VBScript). That cuts out most of the easy languages. Spread your...
6 Feb 2017 by Chris Maunder
Given an array of integers - some positive, some negative, some neither, find the set of consecutive numbers in this array with the largest possible sum. Obviously if all the numbers are positive the answer is the initial array. If all are negative then the answer is an empty array. The...
8 Feb 2017 by Graeme_Grant
Update 3: Added VB.Net versionsHere is another quick one:using System;using System.Collections.Generic;using System.Linq;namespace LargestGroupSum{ static class Program { static void Main(string[] args) { foreach (var test in new...
15 Feb 2017 by Graeme_Grant
Here is my quick solution... Tests done are for nulls List, List elements including nulls, using List elements of Int, String, and complex Object (Car).Update: Added F# conversion of C# and VB.Net.Pick your poison... ummm.. language - F#, C#, or VB.Net. There are also Powershell...
11 Feb 2017 by cigwork
Late to the party; never mind. You want over-engineered? Here we go. The Heath-Robinson* nature of this "solution" is merely a bonus. :D *For USAnian readers : Rube Goldberg.Pseudo-code only 'cos life's too short to actually bother building this rubbish.1. Buy server.2. Buy...
17 Feb 2017 by Jochen Arndt
Quick and dirty for Visual C++ with x86 CPUs (Intel Nehalem and AMD Barcelona or later):#include #include #include using namespace std;int _tmain(int argc, _TCHAR* argv[]){ if (2 != argc) { cout "
24 Mar 2017 by Tomas Takac
This is basically a bubble sort implementation: looping through the sequence, swapping items if they are not in order.class Sorter { private readonly int[] data; private readonly List sortSequence = new List(); public Sorter(int[] data) { this.data =...
31 Mar 2017 by Jon McKee
UPDATED: Fixed a couple bugs including a weighting bug that could cause infinitely swapping the same position. Handles the first two example inputs as shown below but still runs into a stack overflow for larger data sets. I checked and it isn't stuck looping on a single swap, the algorithm just...
31 Mar 2017 by Graeme_Grant
Here is a quick 'n' dirty solution using an API service. Sadly the service is not as good as Grammarly... using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net; namespace TextGearsApi { class Program { static...
14 Feb 2020 by phil.o
Java.util.Scanner.nextInt() Method - Tutorialspoint[^] You don't have to change the variable. If you need to input two distinct values, just call nextInt() method twice. It is also advised to check for the validity of the input, and react...
6 May 2021 by OriginalGriff
The idea of a "code challenge" is to challenge you, not us! If you don't understand a solution you found online, then either learn the fundamentals it is using (including any algorithm(s) it implements) or leave the challenge until your skills...
5 Dec 2022 by merano99
Saving the calories in a vector would be a good idea. std::vector numbers; Then it would be practical to write the calories as described in a file calories.txt and read this file line by line. At each blank line write the sum into the...
22 Mar 2023 by Member 11781538
unsigned bitcnt(unsigned v){ unsigned r= v & 0x55555555u; r= r + ((r^v) >> 1); unsigned s = r & 0x33333333u; s =s + ((s^r) >>2); r= s & 0x0F0F0F0F; r= r + ((r^s)>>4); r *= 0x01010101; return r >> 24; }
9 Nov 2023 by M Imran Ansari
We are here more than happy to help you, but you should try yourself to work on this assignment. Try yourself and come with the issue if you face any. Here is the link to understand the basic concepts of OOP with guide. Introduction to Object...
15 Dec 2016 by Chris Maunder
Greatest Common DenominatorToday's challenge, sent in by Bob Hent, is an oldie and a goodie. Given a list of integers of the form: (n0, n1, n2, … nx)Where (0
26 Nov 2016 by Jon McKee
EDIT: Ah, the wonders sleep can do. Even though a solution was already chosen, I had an idea to improve my solution.This was fun. I don't get to use regex too much in my day to day sadly.using System;using System.Collections.Generic;using System.Text;using...
30 Nov 2016 by PIEBALDconsult
After a little more refactoring and such:PIEBALD.Type.ReplaceOmatic replacer = new PIEBALD.Type.ReplaceOmatic ( new System.Tuple ( "PHB!" , "boss!" ) , new System.Tuple ( "gotten" , "become" ) , new...
27 Nov 2016 by Kornfeld Eliyahu Peter
I saw that no one addressed JavaScript jet...I did...function Bad2Good(text){ var T = { 'poophead': 'p**phead', 'PHB!': 'boss', 'gotten': 'become', 'poop*': 'p**p', '*poop': 'p**p' }; for (var prop in T) { var flags = 'ig'; // starts with if...
28 Nov 2016 by Jacques Sineriz
Quick and dirty Javascriptvar bad = ["poop*", "PHB!", "gotten"];var replacement = ["p**p", "boss", "become"];function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");}function replaceBad(sentence){ return sentence.split(/\b/).map(w =>...
28 Nov 2016 by Graeme_Grant
Only spotted this 20 min ago, so hopefully not too late to the tea party!C# code allows for individual word case sensitivity + shortcut override (in bonus requirement). All cases use the same bad word replacement extension methods. ReplaceWords string extension for a set of words or...
28 Nov 2016 by Harrison Pratt
VISUAL PROLOG 7.5 Solution.Note: the bad_nice/2 clauses can be moved to an external file for maintenance independent of the rest of the code.This could be tidied up more, but I considered speed of submission to be the priority here.Harrison Prattclass predicates ...
28 Nov 2016 by ernst zwecker
I'm a fan of clean code.Which for me is at least: - It should be expressive-> meaningful names - Smaller is better -> methods should be short - Can be easily extended by any other developer -> if requiremets changes easy to adapt - Reading the code should be pleasant ->...
29 Nov 2016 by Stuart Dootson
I decided to use F#…Each filter specification is converted to a closure that takes a string, potentially sanitises it and returns the good string. To process all words in a string, use Regex.Replace with a MatchEvaluator that runs the filter list over the matched word.open Systemopen...
2 Dec 2016 by Graeme_Grant
NOTE: This is a performance summary comparison of the above C# solutions only** Updated 2/12/16: Stuart Dootson supplied test project, so timings updated.I was curious to see how the other C# solutions compared performance wise to my own, so I build a test bed that you can download[^]...
1 Dec 2016 by GeeTee86
setlocal enabledelayedexpansionfor /f "tokens=*" %%a in (h:\myFile.txt) do ( set row=%%a set row=!row:,= ! echo.!row!>>h:\changed.txt)put text in myfile.txtsave as xxx.bat and run via windows command promptit replaces spaces with tabs - because otherwise
2 Dec 2016 by Ramza360
String extension with nice turtle pace immutable string manipulation.public static string RemoveTabs(this string input) { if (string.IsNullOrWhiteSpace(input)) { return input; } int idx = 0; while (true) { if (idx >= input.Length) { ...
2 Dec 2016 by Jacek M Glen
LINQy version of my previous solution. It works properly for tabs placed anywhere in the text, always aligning to %4 (or %tabLength).using System.Linq;using NUnit.Framework;namespace Code_Project_Challenge{ class TabConverter { static int tabLength = 4; ...
2 Dec 2016 by Stuart Dootson
A Haskell solution… Essentially a rough translation of my F# one!{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes #-}module Main whereimport Criterion.Mainimport Data.CaseInsensitive (mk, CI)import Data.Char as Cimport Data.List (find)import Data.Maybe...
2 Dec 2016 by Ken Utting
Javascript, using the replace() function, without using recursion (as in Solution 7). Also, I use a lookup table rather than looping to append the spaces.tabs = [' ', ' ', ' ', ' '];function converTabs(aString) { console.log('source: ' + visualizeWS(aString)); var...
2 Dec 2016 by Mark Miller
Just for fun, how about FoxPro?Convert tabs to 4 spaces or less, as here:* Input: [ ][ ][ ][tab][tab][ ][tab]Hello, world!* Result: [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]Hello, world!** Using all single letter variables just to tick everyone off :)** Clear the screenCLEAR*...
5 Dec 2016 by Kyle Moyer
Actually really simple with Regular Expressions. Just consume the extraneous spaces, then replace all tabs with the correct number of spaces. There's probably optimizations and tricks I missed, but it's Friday, and really can't be arsed.Edit: Just occurred to me that the intermediate step...
2 Dec 2016 by Henrik Jonsson
Of course we also must have a Test Driven Development-in-a-hurry solution, so first write test according to the customer's wishes and also add a "negative" test to get full statement and decision coverage to satisfy the formal unit test checklist and code coverage...
2 Dec 2016 by ClockMeister
I've been needing one of these in my library anyway.// ------------------------------------------------- ///// /// Convert tabs in the input string to spaces./// /// String with imbedded tabs to convert///
2 Dec 2016 by Member 10675068
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Globalization;using System.Threading;namespace TabConversion{ class Program { static void Main(string[] args) { ...
4 Dec 2016 by Patrice T
My solution using xHarbour, xBase family like dBase, Clipper or FoxPro.Note that the language integrate an automatic StringBuilder feature making concatenation always efficient.cleartab= chr(9)test_in=" "+tab+"Hello, world!"? "Input : "print(test_in)? "Output: "test_out=...
3 Dec 2016 by PIEBALDconsult
The C# version I published as Untabify and Tabify[^] acts only on leading whitespace.But, according to the comments, the C version I started with dates back to 2-Jun-1998 -- you might guess from the date format that I was using OpenVMS extensively at the time (and I hadn't yet found out...
3 Dec 2016 by Member 8776409
Here's PHP. You can run it in a terminal window (rather than a browser, which collapses whitespace), using:php -f filename.php$test1 = " \tHello, world!";$test2 = " \t\t \tHello, world!";echo "\nBEFORE... \n\n";echo $test1 . "\n";echo $test2 . "\n";$test1New =...
3 Dec 2016 by Kornfeld Eliyahu Peter
function tab2space(str){ var brk = str.match(/[^\t ]/).index; var wht = str.substr(0, brk); wht = wht.replace(/ /g, '\t').replace(/ {1,3}\t/g, '\t').replace(/\t/g, ' '); return(wht + str.substr(brk));}
3 Dec 2016 by Kornfeld Eliyahu Peter
section .text global _start ; gcc_start: xor ecx, ecx ; counter for spaces mov esi, msg ; original stringmain: mov eax, esi ; get next pos cmp byte [eax], 0x20 jne tab ; chekc for tab inc ecx...
3 Dec 2016 by David O'Neil
Since it is more string handling, I'll simply append solution to previous challenge.New code:In 'reformat' routine:... while (curLocC != endLocC && (isTabOrWhiteSpace(curLocC))) { if (*curLocC == L'\t') { replaceTab(); } else...
3 Dec 2016 by Jon McKee
Ahhhh! I thought this would be posted in the lounge like last time. Glad I caught it! Decided to go with something unique that hasn't been proposed yet =DMight even prove to be useful out-of-the-box if you want to replace tabs in source files in a project directory. I prefer tabs but to...
3 Dec 2016 by Stuart Dootson
Haskell. Just gets the job done.untab tabSize s = foldl processChar "" s where processChar s '\t' = s ++ (replicate (spaceCount s) ' ') processChar s c = s ++ [c] spaceCount s = tabSize - ((length s) `mod` tabSize)with a test harness ofmain = do let s...
4 Dec 2016 by Harrison Pratt
TAB EXPANSION USING VISUAL PROLOG 7.5This approach uses a stream to collect the text, avoiding creation of multiple intermediate strings or managing your own binary buffer.class predicates expandTabs : ( string Input, positive TabSize ) -> string ExpandedString.clauses ...
5 Dec 2016 by Teme64
Here's my solution with C#. Clear, elegant, easy to maintain and... very boring :)string inStr = " \t\t \tHello, world!";string prefixStr;string suffixStr;const int TAB_POS = 4; // TAB_POS > 0int tabPos;// When a tab is found add 1 - TAB_POS filler charstabPos =...
5 Dec 2016 by Pete Lomax Member 10664505
Using Phixfunction expand_tabs(string text, integer tabwidth=4) while 1 do integer tab = find('\t',text) if tab=0 then exit end if text[tab..tab] = repeat(' ',tabwidth-remainder(tab-1,tabwidth)) end while return text&'\n'end functionTest...
5 Dec 2016 by k5054
Here's one in C++:#include std::string tabs_to_spaces(const std::string& input, size_t fill_width){ std::string output; size_t curr_pos = 0; // current position in input string size_t tab_pos; // positions of next tab in input string // find next tab in input...
6 Dec 2016 by Member 8189965
I was going for a one liner in C++void tabit(char* s){ char w[] = " "; for (int i = 0, c = 0, a = 0; s[i] != '\0'; cout
6 Dec 2016 by Member 3981491
Short n sweet... (Can be expanded for readability - but that's not the point here!)C# solution:private string RemoveTabs(string input){ var prefix = new Regex("^[\t ]*").Match(input).Value; return new string(' ', SpaceCountFromPrefix(prefix)) + input.TrimStart('\t', ' ');}private...
11 Dec 2016 by Peter Leow
There are a total of three parts in this solution, read them with patience. :zzz:+++++[Part 1]+++++This is brute-force search with the algorithm as follows:1. GET a list of integers1. SET GCD = 12. SET DIVISOR = 23. WHILE DIVISOR
9 Dec 2016 by Patrice T
Language: Clipper/xHarbourclear? "CCCP Code Chalenge Code Project"? "GCD"lst= {247, 8645, 1216, 3648}ans= gcd(lst)? ansreturnfunction gcd(lst) b= lst[1] for scan=2 to len(lst) a= lst[scan] while (tmp:=a%b) != 0 a= b b= tmp enddo next return bI tried...
9 Dec 2016 by Graeme_Grant
Thanks to Peter Leow[^] for taking the fun out of finding the solution. Whilst he has an interesting solution, I thought that there would be a much faster way of doing it. I like fast code and whilst I did not invent the "Binary Greatest Common Divisor" algorithm (original C version for 2...
10 Dec 2016 by Jon McKee
EDIT: Updated my algorithm to allow a load for the task. MUCH better now (results posted at the end).This was fun. I was already aware of the binary Euclidean algorithm since I've had to calculate GCDs before. So to add my own uniqueness to this problem I decided to work out a way to run...
12 Dec 2016 by Kornfeld Eliyahu Peter
There are no much left as all the math used, but I on my way to create a 6502 (on C=64) solution, so I created a JavaScript prototype, to show that it is possible to do this without actually divide anything...var a = [266, 8664, 1216, 3648];var l = a.length;while (l > 1){ for...