• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 23:21
CET 05:21
KST 13:21
  • 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
RSL Revival - 2025 Season Finals Preview8RSL Season 3 - Playoffs Preview0RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12
Community News
Weekly Cups (Dec 15-21): Classic wins big, MaxPax & Clem take weeklies3ComeBackTV's documentary on Byun's Career !11Weekly Cups (Dec 8-14): MaxPax, Clem, Cure win4Weekly Cups (Dec 1-7): Clem doubles, Solar gets over the hump1Weekly Cups (Nov 24-30): MaxPax, Clem, herO win2
StarCraft 2
General
ComeBackTV's documentary on Byun's Career ! Team TLMC #5: Winners Announced! What's the best tug of war? The Grack before Christmas Weekly Cups (Dec 15-21): Classic wins big, MaxPax & Clem take weeklies
Tourneys
OSC Season 13 World Championship $5,000+ WardiTV 2025 Championship $100 Prize Pool - Winter Warp Gate Masters Showdow Sparkling Tuna Cup - Weekly Open Tournament Winter Warp Gate Amateur Showdown #1
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 505 Rise From Ashes Mutation # 504 Retribution Mutation # 503 Fowl Play Mutation # 502 Negative Reinforcement
Brood War
General
BW General Discussion How soO Began His ProGaming Dreams Klaucher discontinued / in-game color settings BGH Auto Balance -> http://bghmmr.eu/ Recommended FPV games (post-KeSPA)
Tourneys
[Megathread] Daily Proleagues [BSL21] LB SemiFinals - Saturday 21:00 CET [BSL21] WB & LB Finals - Sunday 21:00 CET Small VOD Thread 2.0
Strategy
Simple Questions, Simple Answers Game Theory for Starcraft Current Meta Fighting Spirit mining rates
Other Games
General Games
Nintendo Switch Thread Mechabellum Stormgate/Frost Giant Megathread Beyond All Reason Path of Exile
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
Mafia Game Mode Feedback/Ideas Survivor II: The Amazon Sengoku Mafia TL Mafia Community Thread
Community
General
US Politics Mega-thread 12 Days of Starcraft The Games Industry And ATVI Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine
Fan Clubs
White-Ra Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece
Sports
2024 - 2026 Football Thread Formula 1 Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List TL+ Announced Where to ask questions and add stream?
Blogs
National Diversity: A Challe…
TrAiDoS
I decided to write a webnov…
DjKniteX
James Bond movies ranking - pa…
Topin
Thanks for the RSL
Hildegard
Saturation point
Uldridge
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1466 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
Hyrule19184 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
Poland17546 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
Next event in 5h 39m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
WinterStarcraft410
RuFF_SC2 232
NeuroSwarm 227
StarCraft: Brood War
Shuttle 165
NaDa 66
GoRush 41
Icarus 5
Zeus 0
eros_byul 0
Dota 2
monkeys_forever482
LuMiX1
League of Legends
JimRising 623
C9.Mang0403
Heroes of the Storm
Khaldor120
Other Games
summit1g6258
tarik_tv6230
XaKoH 110
Mew2King68
minikerr30
Organizations
Other Games
gamesdonequick1498
BasetradeTV77
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 17 non-featured ]
StarCraft 2
• intothetv
• IndyKCrew
• sooper7s
• AfreecaTV YouTube
• Migwel
• LaughNgamezSOOP
• Kozan
StarCraft: Brood War
• Azhi_Dahaki28
• Pr0nogo 1
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• masondota22258
League of Legends
• Rush811
• Stunt456
• Lourlo405
Other Games
• Scarra669
Upcoming Events
Sparkling Tuna Cup
5h 39m
Krystianer vs Classic
TriGGeR vs SKillous
Percival vs Ryung
ByuN vs Nicoract
OSC
13h 39m
BSL 21
15h 39m
Cross vs Dewalt
Replay Cast
1d 4h
Wardi Open
1d 7h
OSC
2 days
Solar vs MaxPax
ByuN vs Krystianer
Spirit vs TBD
OSC
5 days
Korean StarCraft League
5 days
OSC
6 days
OSC
6 days
Liquipedia Results

Completed

Escore Tournament S1: W1
WardiTV 2025
META Madness #9

Ongoing

C-Race Season 1
IPSL Winter 2025-26
BSL Season 21
CSL Season 19: Qualifier 2
eXTREMESLAND 2025
SL Budapest Major 2025
ESL Impact League Season 8
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025

Upcoming

CSL 2025 WINTER (S19)
Escore Tournament S1: W2
Escore Tournament S1: W3
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
Bellum Gens Elite Stara Zagora 2026
HSC XXVIII
Big Gabe Cup #3
OSC Championship Season 13
Nations Cup 2026
ESL Pro League Season 23
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
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.