• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 13:16
CET 19:16
KST 03:16
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
TL.net Map Contest #21: Winners11Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13TL.net Map Contest #21: Voting12[ASL20] Ro4 Preview: Descent11
Community News
StarCraft, SC2, HotS, WC3, Returning to Blizzcon!45$5,000+ WardiTV 2025 Championship7[BSL21] RO32 Group Stage4Weekly Cups (Oct 26-Nov 2): Liquid, Clem, Solar win; LAN in Philly2Weekly Cups (Oct 20-26): MaxPax, Clem, Creator win10
StarCraft 2
General
SC: Evo Complete - Ranked Ladder OPEN ALPHA Mech is the composition that needs teleportation t TL.net Map Contest #21: Winners StarCraft, SC2, HotS, WC3, Returning to Blizzcon! RotterdaM "Serral is the GOAT, and it's not close"
Tourneys
Constellation Cup - Main Event - Stellar Fest Sparkling Tuna Cup - Weekly Open Tournament $5,000+ WardiTV 2025 Championship Merivale 8 Open - LAN - Stellar Fest Sea Duckling Open (Global, Bronze-Diamond)
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 499 Chilling Adaptation Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection
Brood War
General
FlaSh on: Biggest Problem With SnOw's Playstyle BGH Auto Balance -> http://bghmmr.eu/ [ASL20] Ask the mapmakers — Drop your questions BW General Discussion Where's CardinalAllin/Jukado the mapmaker?
Tourneys
[Megathread] Daily Proleagues [ASL20] Grand Finals [BSL21] RO32 Group A - Saturday 21:00 CET [BSL21] RO32 Group B - Sunday 21:00 CET
Strategy
PvZ map balance Current Meta How to stay on top of macro? Soma's 9 hatch build from ASL Game 2
Other Games
General Games
Stormgate/Frost Giant Megathread Should offensive tower rushing be viable in RTS games? Nintendo Switch Thread Path of Exile Dawn of War IV
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine Canadian Politics Mega-thread US Politics Mega-thread The Games Industry And ATVI
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Learning my new SC2 hotkey…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Our Last Hope in th…
KrillinFromwales
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1383 users

The Big Programming Thread - Page 859

Forum Index > General Forum
Post a Reply
Prev 1 857 858 859 860 861 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
Nesserev
Profile Blog Joined January 2011
Belgium2760 Posts
Last Edited: 2017-03-09 22:14:58
March 09 2017 22:03 GMT
#17161
--- Nuked ---
netherh
Profile Blog Joined November 2011
United Kingdom333 Posts
Last Edited: 2017-03-09 22:31:33
March 09 2017 22:30 GMT
#17162
On March 10 2017 07:03 Nesserev wrote:
Show nested quote +
On March 10 2017 05:09 Blisse wrote:
5-minute hard limit. Time yourself.

Find the longest palindromic substring in a list of strings.

For example, given strings: "carracecar", "aabbaa", "aabbbabab", return either "racecar" or 7.

I don't see how you could write any decent code under 5 minutes to solve this problem.


Yeah. Took me about 15 minutes to create a basic solution and realise it didn't work, 30 minutes of trying to remember how reverse_iterators work (yay C++), and another 15 minutes of fiddling around and fixing edge cases.

Googling shows there are better ways of doing this (and would be the first step anywhere other than interviews I guess...).

+ Show Spoiler +



#include <string>
#include <array>
#include <iostream>
#include <algorithm>
#include <cassert>

int main(int, char*[])
{
auto input = std::array<std::string, 9u>{ "", "a", "ab", "abc", "aa", "cac", "aabbbabab", "aabbaa", "carracecar" };

auto best = std::string();

for (auto const& s : input)
{
if (s.size() < 2u)
continue;

// won't find a longer palindrome in a shorter or equal string
if (s.size() <= best.size())
continue;

std::cout << "checking: " << s << std::endl;

for (auto i = s.begin(); std::next(i) != s.end(); ++i)
{
using RIt = std::reverse_iterator<std::string::const_iterator>;

// i is the start of a palindrome (e.g. the first 'a' in "aa")
auto even = std::mismatch(std::next(i), s.end(), RIt(std::next(i)), s.rend());

auto even_first = even.second.base();
auto even_last = even.first;
auto even_length = std::distance(even_first, even_last);

assert(even_length >= 0);
auto even_length_u = static_cast<unsigned int>(even_length);

if (even_length_u > 1 && even_length_u > best.size())
best = std::string(even_first, even_last);

// i is the middle of a palindrome (e.g. the 'a' in "cac")
auto odd = std::mismatch(std::next(i), s.end(), RIt(i), s.rend());

auto odd_first = odd.second.base();
auto odd_last = odd.first;
auto odd_length = std::distance(odd_first, odd_last);

assert(odd_length >= 0);
auto odd_length_u = static_cast<unsigned int>(odd_length);

if (odd_length_u > 1 && odd_length_u > best.size())
best = std::string(odd_first, odd_last);
}

std::cout << "best so far: " << best << " " << best.size() << std::endl;
}

std::cout << "best: " << best << " " << best.size() << std::endl;
}


slmw
Profile Blog Joined October 2010
Finland233 Posts
March 09 2017 22:36 GMT
#17163
O(N^2) per word should be simple enough to do in five minutes for anyone with a bit of competitive programming practice. O(N) is quite a bit tougher with all the index fiddling and potential one off errors.
Khalum
Profile Joined September 2010
Austria831 Posts
Last Edited: 2017-03-10 01:19:30
March 10 2017 01:18 GMT
#17164
5 minutes are more than enough for a trivial approach. It won't be pretty but it should work.

I'm curious why the string as well as the length are valid outputs. The approach is the same?
meatpudding
Profile Joined March 2011
Australia520 Posts
March 10 2017 01:25 GMT
#17165
This took me 7 minutes and it still doesn't quite work. Basic idea is to "fan out" both ways from each character and stop when the palindrome ends. Store the longest palindrome word and print it.

def palin(s):
longest_n = 0
longest_start = 0
start = 0
end = 0
for i in range(len(s)):
start = i
end = i
while (s >= 0 and end < len(s)):
if (s[start] == s[end]):
n = end - start + 1
if (n > longest_n):
longest_n = n
longest_start = start
else:
break
start -= 1
end += 1

print longest_n, s[longest_start:longest_start + longest_n]


palin("carracecar")
palin("aabbaa")
palin("aabbbabab")


Output:

7 racecar
3
5 abbba


I only just realised that this will only work for odd palindromes.
Be excellent to each other.
tofucake
Profile Blog Joined October 2009
Hyrule19151 Posts
March 10 2017 01:43 GMT
#17166
I just had an interview today with a palindrome question. In JS it takes about 30 seconds to read the instructions, think, then type out

function isPalindrome(possiblePalindrome) {
return possiblePalindrome == possiblePalindrome.split('').reverse().join('').toString();
}


making it support an array and finding the longest palindrome of the bunch is another 2 minutes :\
Liquipediaasante sana squash banana
Hanh
Profile Joined June 2016
146 Posts
March 10 2017 01:55 GMT
#17167
Still too long! Heh

 
let is_palindrome s = rev s = s
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-10 02:33:28
March 10 2017 02:24 GMT
#17168
This is what I did. took 15-20 min cuz i kept making stupid mistakes



public static int find(ArrayList<String> words) {
int size = 1;
int total = 0;
for(String w : words) {

for(int i = 0; i < w.length() - 1; i++) {
int front = 1, back = 1;
while(((i - back >= 0) && (i + front <= w.length() - 1) && (w.charAt(i + front) == w.charAt(i - back)))) {
size += 2;
back++;
front++;
}
if (size > total) {
total = size;
}
size = 1;
}
}
return total;
}



pretty sure this is O(n) unless we are dealing with the longest strings of all time

I didn't record the actual string because blisse said I didn't have to. but I could if I needed to it would just be a very mildly painful addition

edit: I guess slmw was talking about beating O(n^2) per word, which makes more sense because why would you have to iterate through words more than once

So looking at the complexity of this per word... mmmm..
I really am not sure? I guess it's technically O(n^2) but it's like a really good O(n^2), and that's worst case.

maybe someone who is good at complexity could look at this and tell me what the complexity per word is?
slmw
Profile Blog Joined October 2010
Finland233 Posts
March 10 2017 02:37 GMT
#17169
Simplest O(N^2) per word implementation I could think of, very similar to your python solution. O(N) per word was quite a bit tougher to do and definitely over 5 minutes. :D

On March 10 2017 10:18 Khalum wrote:
I'm curious why the string as well as the length are valid outputs. The approach is the same?


It's just basically a matter of formatting the output.

On March 10 2017 10:43 tofucake wrote:
I just had an interview today with a palindrome question. In JS it takes about 30 seconds to read the instructions, think, then type out

function isPalindrome(possiblePalindrome) {
return possiblePalindrome == possiblePalindrome.split('').reverse().join('').toString();
}


making it support an array and finding the longest palindrome of the bunch is another 2 minutes :\


You gotta still create all the substrings though so a bit more programming left to do!. Also this is O(N^3) per word!

On March 10 2017 11:24 travis wrote:
This is what I did. took 15-20 min cuz i kept making stupid mistakes



public static int find(ArrayList<String> words) {
int size = 1;
int total = 0;
for(String w : words) {

for(int i = 0; i < w.length() - 1; i++) {
int front = 1, back = 1;
while(((i - back >= 0) && (i + front <= w.length() - 1) && (w.charAt(i + front) == w.charAt(i - back)))) {
size += 2;
back++;
front++;
}
if (size > total) {
total = size;
}
size = 1;
}
}
return total;
}



pretty sure this is O(n) unless we are dealing with the longest strings of all time

I didn't record the actual string because blisse said I didn't have to. but I could if I needed to it would just be a very mildly painful addition

edit: I guess slmw was talking about beating O(n^2) per word, which makes more sense because why would you have to iterate through words more than once

So looking at the complexity of this per word... mmmm..
I really am not sure? I guess it's technically O(n^2) but it's like a really good O(n^2), and that's worst case.


This is O(N^2) per word, but doesn't it work just for odd palindromes? https://ideone.com/ke4q0k
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-10 02:39:50
March 10 2017 02:38 GMT
#17170
oh duh of course it only works for odd palindromes

looking up i probably did whatever meatpudding was doing

tbh I never even realized it was a palindrome if it wasn't odd, lol. the problem would be a million times harder for me including even palindromes

basically I'd be writing all separate code to handle even palindromes
it'd still be O(n^2) though
WarSame
Profile Blog Joined February 2010
Canada1950 Posts
March 10 2017 05:11 GMT
#17171
Do any of you know a good place to go for code review? I want to have my git repo checked to see if there are better coding decisions I could have made. Is there some sort of dedicated area or site for that?
Can it be I stayed away too long? Did you miss these rhymes while I was gone?
ShoCkeyy
Profile Blog Joined July 2008
7815 Posts
March 10 2017 05:57 GMT
#17172
WarSame depending on the language, you can ask some one in the freenode irc chat. I'm sure some one there or here would be willing to review.
Life?
Hanh
Profile Joined June 2016
146 Posts
March 10 2017 06:05 GMT
#17173
On March 10 2017 11:38 travis wrote:
oh duh of course it only works for odd palindromes

looking up i probably did whatever meatpudding was doing

tbh I never even realized it was a palindrome if it wasn't odd, lol. the problem would be a million times harder for me including even palindromes

basically I'd be writing all separate code to handle even palindromes
it'd still be O(n^2) though


Don't worry too much about performance. Focus on correctness first. There is no point in returning a wrong result quickly.
Looking back at this thread, the people who talk about how easy the question is have yet to give a good answer.
Manit0u
Profile Blog Joined August 2004
Poland17423 Posts
March 10 2017 08:04 GMT
#17174
On March 10 2017 14:11 WarSame wrote:
Do any of you know a good place to go for code review? I want to have my git repo checked to see if there are better coding decisions I could have made. Is there some sort of dedicated area or site for that?


What language? I love code reviews
Time is precious. Waste it wisely.
Cynry
Profile Blog Joined August 2010
810 Posts
Last Edited: 2017-03-10 12:04:29
March 10 2017 08:56 GMT
#17175
Anyone here knows golang, and have used the mongodb official drivers (mgo) ?
I've been working for almost 2 years with mongo in js without an issue, but ever since I started go every single query that I have to do is a pain in the ass.

It's my first project in go, soooo todolist it is !
And here's the query that is driving me nuts lately:
func (u *User) getNextTask(date time.Time) (Task, error) {
task := Task{}
query := bson.M{
"id": bson.M{"$in": u.Tasks},
"timestamp": bson.M{"$gte": date},
}
err := Tasks.Find(query).Sort("timestamp").Limit(1).One(&task)
if err != nil {
return task, err
}
return task, nil
}

Simply receives a date, get the tasks that have been created after, sort them by ascending order to get the next one, limit to one result, etc. It doesn't even get here anyway.
The query doesn't return anything, although everything I've checked is correct. I receive a proper date, u.Tasks does contain an array of bson.ObjectIds (the query works when I remove the timestamp part, so this is fine). There is at the moment of the tests, at least a task that has should match the query (same user, created after, can be checked if I do the same query without the timestamp part).
So it apparently comes from that very line

"timestamp": bson.M{"$gte": date},

but I can't see what's wrong with it. At this point I suspect a typo or something silly like that, but I seem to need an exterior look... So, anyone ?

Palindrome challenge: All I could come up in 5 minutes was some pseudo code that didn't work for odd palindromes... forgot about those ^^
Khalum
Profile Joined September 2010
Austria831 Posts
Last Edited: 2017-03-10 10:39:13
March 10 2017 10:34 GMT
#17176
On March 10 2017 15:05 Hanh wrote:
[..]
Looking back at this thread, the people who talk about how easy the question is have yet to give a good answer.



Fair point! I had just come home from a night of drinking and would definately not have given a good answer then
Am still a bit drunk but I gave it a shot to put my money where my mouth was. My solution is probably not correct. I hacked it in 7 minutes (yes, more than 5...) so I guess I failed anyways. Now back to sleep.


int palindromeLength(string s)
{
for (int i=0; i<s.length()/2; ++i)
{
if (s[i] != s[s.length()-1-i])
{
return 0;
}
}
return s.length();
}

int getLongestPalindrome(string s)
{
int maxLen = 0;
for (string::iterator ita=s.begin(); ita<s.end()-maxLen-1; ++ita)
{
for (string::iterator itb=ita+maxLen+1; itb<s.end(); ++itb)
{
maxLen = max(maxLen, palindromeLength(string(ita,itb)));
}
}
return maxLen;
}



[edit]
This is missing a function that calls getLongestPalindrome() with some strings to be tested and collects the max of these.

[edit2]
Fixed 2 errors. Yes, I cheat.
netherh
Profile Blog Joined November 2011
United Kingdom333 Posts
Last Edited: 2017-03-10 13:46:06
March 10 2017 13:42 GMT
#17177
On March 10 2017 14:11 WarSame wrote:
Do any of you know a good place to go for code review? I want to have my git repo checked to see if there are better coding decisions I could have made. Is there some sort of dedicated area or site for that?


Well there's this:

http://codereview.stackexchange.com/

I think you're supposed to include code in the question though, so depends on how large your repo is, or if you can extract specific bits of code.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-10 14:09:55
March 10 2017 14:04 GMT
#17178
Situation in C:

I want to pass a char pointer to a function.
Then go through the memory, and find integers.
Store those integers into a character array.
And then return the pointer to the new character array (that only holds the integers).

But because my character array is local to the function it becomes garbage when my function ends, so this doesn't work
But I am not supposed to use dynamic memory allocation, and im not supposed to use global variables

so how do I do what I am describing?


edit: is what I need to do, to declare my character array before i call my function, and then pass a pointer to it to my function? god I hate C
slmw
Profile Blog Joined October 2010
Finland233 Posts
March 10 2017 14:17 GMT
#17179
If you allocate an array on the stack it gets cleaned up when you exit the function scope. If you allocate it on the heap, you're responsible for cleaning it up. If you need to do it on the stack, do everything before you exit the stack scope. It isn't that different from other languages.
waffelz
Profile Blog Joined June 2012
Germany711 Posts
March 10 2017 16:05 GMT
#17180
On March 09 2017 05:57 Nesserev wrote:
Show nested quote +
On March 09 2017 05:01 waffelz wrote:
Can someone recommend a good ARM-emulator, preferably with some tools to inspect memory etc, support of C would be nice too but not a must. OS would be preferably windows, but linux would work too.

Have you checked out qemu yet? (http://www.qemu-project.org/)


I haven't, but I will check it out, Thanks for the suggestion.
RIP "The big travis CS degree thread", taken from us too soon | Honourable forum princess, defended by Rebs-approved white knights
Prev 1 857 858 859 860 861 1032 Next
Please log in or register to reply.
Live Events Refresh
Wardi Open
12:00
#60
WardiTV2250
IndyStarCraft 228
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
IndyStarCraft 235
UpATreeSC 87
StarCraft: Brood War
Rain 3549
Horang2 1587
Shuttle 779
firebathero 160
scan(afreeca) 52
sSak 37
Mong 30
Aegong 22
JulyZerg 17
ivOry 6
[ Show more ]
SilentControl 5
Dota 2
Gorgc5362
qojqva3580
420jenkins277
BananaSlamJamma178
XcaliburYe153
League of Legends
rGuardiaN20
Counter-Strike
fl0m572
byalli525
Other Games
FrodaN1033
Beastyqt715
ceh9567
KnowMe280
Lowko263
Sick257
Hui .188
Mew2King150
Liquid`VortiX147
ArmadaUGS79
QueenE48
Trikslyr46
Organizations
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 18 non-featured ]
StarCraft 2
• kabyraGe 105
• Reevou 1
• IndyKCrew
• LaughNgamezSOOP
• sooper7s
• AfreecaTV YouTube
• Migwel
• intothetv
• Kozan
StarCraft: Brood War
• Michael_bg 9
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• WagamamaTV218
League of Legends
• Nemesis3571
• TFBlade957
• imaqtpie471
Other Games
• Shiphtur284
Upcoming Events
Replay Cast
4h 44m
WardiTV Korean Royale
17h 44m
OSC
22h 44m
Replay Cast
1d 4h
Replay Cast
1d 14h
Kung Fu Cup
1d 17h
Classic vs Solar
herO vs Cure
Reynor vs GuMiho
ByuN vs ShoWTimE
Tenacious Turtle Tussle
2 days
The PondCast
2 days
RSL Revival
2 days
Solar vs Zoun
MaxPax vs Bunny
Kung Fu Cup
2 days
[ Show More ]
WardiTV Korean Royale
2 days
PiGosaur Monday
3 days
RSL Revival
3 days
Classic vs Creator
Cure vs TriGGeR
Kung Fu Cup
3 days
CranKy Ducklings
4 days
RSL Revival
4 days
herO vs Gerald
ByuN vs SHIN
Kung Fu Cup
4 days
BSL 21
5 days
Tarson vs Julia
Doodle vs OldBoy
eOnzErG vs WolFix
StRyKeR vs Aeternum
Sparkling Tuna Cup
5 days
RSL Revival
5 days
Reynor vs sOs
Maru vs Ryung
Kung Fu Cup
5 days
WardiTV Korean Royale
5 days
BSL 21
6 days
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
Wardi Open
6 days
Monday Night Weeklies
6 days
Liquipedia Results

Completed

Proleague 2025-11-07
Stellar Fest: Constellation Cup
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual

Upcoming

SLON Tour Season 2
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
RSL Revival: Season 3
META Madness #9
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.