• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 09:22
CEST 15:22
KST 22:22
  • 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
Serral wins HomeStory Cup 2914Serral wins Maestros of the Game 243ByuL, and the Limitations of Standard Play3Team Liquid Map Contest #22: Results and Winners7Code S Season 2 (2026): RO4 and Finals Preview12
Community News
Balance hotfix patch 5.0.16b (July 16)18Reynor: GSL Loss Wasn't About Preparation Format16[IPSL] Spring 2026 Grand Finals - This Weekend!5Weekly Cups (July 6 - 12): Protoss strike back12BSL Season 22 Full Overview & Conclusion8
StarCraft 2
General
Balance hotfix patch 5.0.16b (July 16) Reynor: GSL Loss Wasn't About Preparation Format Is the larve respawn broken? 5.0.16 patch for SC2 goes live (8 worker start) BGE Stara Zagora to be held again in June 2025
Tourneys
Master Swan Open (Global Bronze-Master 2) WardiTV Summer Cup 2026 GSL CK #5 Race War RSL Revival: Season 6 - Qualifiers and Main Event HomeStory Cup 29
Strategy
[G] Having the right mentality to improve
Custom Maps
New Map Maker - Looking for Advice - Love or Hate Work In Progress Melee Maps [D]RTS in all its shapes and glory <3
External Content
The PondCast: SC2 News & Results Mutation # 534 Burning Evacuation Mutation # 533 Die Together Mutation # 532 Nuclear Family
Brood War
General
Etiquete rules in Asl? Recommended FPV games (post-KeSPA) Pros Debate: Zerg Unfairly Nerfed? (ASL S22 map) BGH Auto Balance -> http://bghmmr.eu/ screpdb: new Starcraft reporting tool
Tourneys
Escore Tournament - Season 3 Small VOD Thread 2.0 [IPSL] Spring 2026 Grand Finals - This Weekend! [Megathread] Daily Proleagues
Strategy
Fighting Spirit mining rates Simple Questions, Simple Answers Creating a full chart of Zerg builds Relatively freeroll strategies
Other Games
General Games
Path of Exile General RTS Discussion Thread Nintendo Switch Thread Beyond All Reason Stormgate/Frost Giant Megathread
Dota 2
Looking for a Dota Mentor 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
TL Mafia
TL Mafia Power Rank NeO.D_StephenKing vs This Guy From 1 Million Dance TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread UK Politics Mega-thread YouTube Thread Canadian Politics Mega-thread
Fan Clubs
The IdrA Fan Club The HerO Fan Club!
Media & Entertainment
Movie Discussion! Anime Discussion Thread [Req][Books] Good Fantasy/SciFi books Series you have seen recently...
Sports
2024 - 2026 Football Thread MLB/Baseball 2023 McBoner: A hockey love story Tennis[sport] Formula 1 Discussion
World Cup 2022
Tech Support
Simple Questions Simple Answers FPS when play League Of Legend on laptop How to clean a TTe Thermaltake keyboard?
TL Community
Northern Ireland Global Starcraft The Automated Ban List
Blogs
Poker (part 2)
Nebuchad
The Experiences We Want and …
TrAiDoS
An Exploration of th…
waywardstrategy
Gauntlet SC2: A Retrospectiv…
Ctone23
ramps on octagon
StaticNine
Funny Nicknames
LUCKY_NOOB
Evil Gacha Games and the…
ffswowsucks
Customize Sidebar...

Website Feedback

Closed Threads



Active: 7990 users

The Big Programming Thread - Page 409

Forum Index > General Forum
Post a Reply
Prev 1 407 408 409 410 411 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.
WarSame
Profile Blog Joined February 2010
Canada1950 Posts
December 16 2013 17:58 GMT
#8161
That explains the weird Syntax...
Can it be I stayed away too long? Did you miss these rhymes while I was gone?
Fairon
Profile Blog Joined January 2011
Russian Federation80 Posts
December 16 2013 21:31 GMT
#8162
On December 17 2013 02:58 WarSame wrote:
That explains the weird Syntax...


But still, why can't I run the code you wrote?
CalendarWork Hard, Go Pro @artemfairon
WarSame
Profile Blog Joined February 2010
Canada1950 Posts
December 16 2013 22:43 GMT
#8163
I'm not sure. The error you posted mentions that it is an error with the Scanner and Random parts. So did you include the
import java.util.Random;
import java.util.Scanner;
section?
Can it be I stayed away too long? Did you miss these rhymes while I was gone?
Fairon
Profile Blog Joined January 2011
Russian Federation80 Posts
December 17 2013 10:42 GMT
#8164
On December 17 2013 07:43 WarSame wrote:
I'm not sure. The error you posted mentions that it is an error with the Scanner and Random parts. So did you include the
Show nested quote +
import java.util.Random;
import java.util.Scanner;
section?


You are right, that's what I forgot to include. Now everything works perfectly.
I have to improve my attentiveness, it looks like that's very important thing to have while coding.
CalendarWork Hard, Go Pro @artemfairon
Manit0u
Profile Blog Joined August 2004
Poland17792 Posts
Last Edited: 2013-12-18 17:37:19
December 18 2013 17:35 GMT
#8165
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...


#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i])
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j])
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i]);
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.
Time is precious. Waste it wisely.
Deleted User 101379
Profile Blog Joined August 2010
4849 Posts
Last Edited: 2013-12-18 18:04:35
December 18 2013 18:04 GMT
#8166
On December 19 2013 02:35 Manit0u wrote:
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...

+ Show Spoiler +


#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i]
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j]
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i];
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.


Untested since i'm too lazy, but this is a very simple shuffle implementation:

int array[5] = { 1,2,3,4,5 };
for (int i = 0; i < 5; ++i)
{
int new_pos = rand() % 5;
int temp = array[i];
array[i] = array[new_pos];
array[new_pos] = temp;
}


Basically, for every element in the array, you pick a random index and exchange the current element with the element at that index.
scudst0rm
Profile Joined May 2010
Canada1149 Posts
Last Edited: 2013-12-18 18:06:40
December 18 2013 18:05 GMT
#8167
On December 19 2013 02:35 Manit0u wrote:
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...

+ Show Spoiler +

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i]
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j]
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i];
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.


Your while loop condition doesn't make sense. while (number == order[i]) will only be true on the first iteration when both are 0. after that you update number to a random value but order[i] will still be 0.
You're like a one ranger army comin' at me...
Manit0u
Profile Blog Joined August 2004
Poland17792 Posts
Last Edited: 2013-12-18 20:19:25
December 18 2013 18:16 GMT
#8168
On December 19 2013 03:05 scudst0rm wrote:
Show nested quote +
On December 19 2013 02:35 Manit0u wrote:
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...

+ Show Spoiler +

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i]
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j]
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i];
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.


Your while loop condition doesn't make sense. while (number == order[i]) will only be true on the first iteration when both are 0. after that you update number to a random value but order[i] will still be 0.


I knew I messed something up with the control statements and placement of things That's what you get for having 2 minutes at the computer and having to do different stuff for hours inbetween.

On December 19 2013 03:04 Morfildur wrote:
Show nested quote +
On December 19 2013 02:35 Manit0u wrote:
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...

+ Show Spoiler +


#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i]
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j]
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i];
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.


Untested since i'm too lazy, but this is a very simple shuffle implementation:

int array[5] = { 1,2,3,4,5 };
for (int i = 0; i < 5; ++i)
{
int new_pos = rand() % 5;
int temp = array[i];
array[i] = array[new_pos];
array[new_pos] = temp;
}


Basically, for every element in the array, you pick a random index and exchange the current element with the element at that index.


Tried it like that:


#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
srand((unsigned int) time(0));

int arr[5] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr);

while (n > 1)
{
int s = rand() % n;
int tmp = arr[n];

n -= 1;
arr[s] = arr[n];
arr[n] = tmp;
}

for (int i = 0; i < 5; i += 1)
{
printf("%d, ", arr[i]);
}

return 0;
}


It compiles just fine but throws the "memory protection error" at me. Any ideas where I went wrong?

Edit: This works but not as intended (some of the elements get doubled).


srand((unsigned int) time(0));

int arr[5] = { 1, 2, 3, 4, 5 };

for (int i = 0; i < 5; i += 1)
{
int s = rand() % 5;
int tmp = arr[i];

arr[i] = arr[s];
arr[s] = tmp;

printf("%d\n", arr[i]);
}


Edit2: I'm dumb... Forget about it
Time is precious. Waste it wisely.
Vilanoil
Profile Blog Joined July 2010
Germany47 Posts
December 18 2013 21:56 GMT
#8169
Hello, i need some help with linked lists in java. It's a program i have to write for my course and i can't find my error.
I am not allowed to use the API class for lists.
I somehow have a problem with my tail function which has to return a new list with out the head.

+ Show Spoiler +

// get rest of list
// note: this operation must create a new list (which may be empty = null)
PlayerList tail()
{
PlayerList list = new PlayerList(head().getNext());
if(list.head() == null)
{
PlayerList empty = new PlayerList();
return empty;
}
return list;

}


my constructors for the list:
+ Show Spoiler +

// constructor for empty list
PlayerList()
{
firstPlayer = null;
}

// constructor to start list with first player
PlayerList(Player playr)
{
firstPlayer = playr;
}


and well .. head().getNext() returns the 2nd Player object.

With the code like this i always get an java.lang.StackOverflowError. So i think it means that when i call tail() in my recursive functions it doens'f find the end of the list. But i can't figure out why.
Help please
WarSame
Profile Blog Joined February 2010
Canada1950 Posts
December 18 2013 22:05 GMT
#8170
Maybe you need to check if the list is 1 or less elements?
Can it be I stayed away too long? Did you miss these rhymes while I was gone?
bangsholt
Profile Joined June 2011
Denmark138 Posts
December 18 2013 23:06 GMT
#8171
How is the rest of your linked list implemented, and how are you using it, because I don't see something that should give you a stack overflow there.

Also you should check for null, then make a new list, as you're otherwise making a list that consists of a null player - which probably is not what you want.

Vilanoil
Profile Blog Joined July 2010
Germany47 Posts
Last Edited: 2013-12-18 23:21:45
December 18 2013 23:17 GMT
#8172
On December 19 2013 08:06 bangsholt wrote:
How is the rest of your linked list implemented, and how are you using it, because I don't see something that should give you a stack overflow there.

Also you should check for null, then make a new list, as you're otherwise making a list that consists of a null player - which probably is not what you want.


Thats the complete class:

+ Show Spoiler +

public class PlayerList
{
private Player firstPlayer;

// constructor for empty list
PlayerList()
{
firstPlayer = null;
}

// constructor to start list with first player
PlayerList(Player playr)
{
firstPlayer = playr;
}

// *************************************************************************
// setter for first element
void setHead(Player playr)
{
firstPlayer = playr;
}

// *************************************************************************
// getter for first element
Player head()
{
return firstPlayer;
}

// *************************************************************************
// get rest of list
// note: this operation must create a new list (which may be empty = null)
PlayerList tail()
{
PlayerList list = new PlayerList(head().getNext());
if(list.head() == null){
final PlayerList empty = new PlayerList();
return empty;
}
return list;

}

// *************************************************************************
// add each new Student at the beginning of the list
void addPlayer(Player playr)
{
playr.setNext(head());
setHead(playr);
}

// *************************************************************************
// add each new Student recursively at the end of the list
void addPlayerLast(Player playr, PlayerList list)
{
if(list.head().getNext() == null){
list.head().setNext(head().getNext());
}
else{
addPlayerLast(playr, tail());
}

}

// *************************************************************************
void addPlayerLast(Player playr)
{
addPlayerLast(playr, this);
}

// *************************************************************************
// recursive print-out of player data (id, family name, first name, goals)
void printList(PlayerList list)
{
if(head() == null){
}
else{
//System.out.println(head().toString());
printList(tail());
}
}

// *************************************************************************
// just call printList(param) to allow for recursion and to keep the interface clean
void printList()
{
printList(this);
}

// *************************************************************************
// recursive computation of length of list
int lengthList(PlayerList list)
{
if(firstPlayer.getNext() == null){
return 1;
}
else{
return 1+lengthList(tail());
}
}

// *************************************************************************
int lengthList()
{
return lengthList(this);
}

// *************************************************************************
// recursive computation of sum of ages of all players in the list
int sumAge(PlayerList list)
{
if(firstPlayer.getNext() == null){
return firstPlayer.getAge();
}
else{

return head().getAge() + sumAge(tail());

}
}

// *************************************************************************
// recursive computation of sum of games of all players in the list
int sumAge()
{
return sumAge(this);
}

// *************************************************************************
/**
* @param args
*/
public static void main(String[] args)
{

PlayerList test = new PlayerList();
Player ilkay = new Player(1, "Guendokan", "Ilkay", 23, "Stauchung");
test.addPlayer(ilkay);
Player mats = new Player(2, "Hummels", "Mats", 24, "Baenderriss");
test.addPlayer(mats);
Player neven = new Player(3, "Subotic", "Neven", 25, "Kreuzbandriss");
test.addPlayer(neven);
Player sven = new Player(4, "Bender", "Sven", 24, "Innenbandanriss");
test.addPlayer(sven);
Player nuri = new Player(5, "Sahin", "Nuri", 25, "Sprunggelenk");
test.addPlayer(nuri);

System.out.println(test.sumAge());
System.out.println(test.head().getFamilyName()); // testing

//players.printList();
//System.out.println("length of list: " + test.lengthList());
//System.out.println("average age: " + (double) players.sumAge()/players.lengthList() + "\n");

}
}



Basically all methods with tail() do not work, the others like addPlayer work.

And regarding that null player list ... that's what it was says in the description: must create a new list (which may be empty = null)
WolfintheSheep
Profile Joined June 2011
Canada14127 Posts
December 18 2013 23:45 GMT
#8173
On December 19 2013 08:17 Vilanoil wrote:
Show nested quote +
On December 19 2013 08:06 bangsholt wrote:
How is the rest of your linked list implemented, and how are you using it, because I don't see something that should give you a stack overflow there.

Also you should check for null, then make a new list, as you're otherwise making a list that consists of a null player - which probably is not what you want.


Thats the complete class:

+ Show Spoiler +

public class PlayerList
{
private Player firstPlayer;

// constructor for empty list
PlayerList()
{
firstPlayer = null;
}

// constructor to start list with first player
PlayerList(Player playr)
{
firstPlayer = playr;
}

// *************************************************************************
// setter for first element
void setHead(Player playr)
{
firstPlayer = playr;
}

// *************************************************************************
// getter for first element
Player head()
{
return firstPlayer;
}

// *************************************************************************
// get rest of list
// note: this operation must create a new list (which may be empty = null)
PlayerList tail()
{
PlayerList list = new PlayerList(head().getNext());
if(list.head() == null){
final PlayerList empty = new PlayerList();
return empty;
}
return list;

}

// *************************************************************************
// add each new Student at the beginning of the list
void addPlayer(Player playr)
{
playr.setNext(head());
setHead(playr);
}

// *************************************************************************
// add each new Student recursively at the end of the list
void addPlayerLast(Player playr, PlayerList list)
{
if(list.head().getNext() == null){
list.head().setNext(head().getNext());
}
else{
addPlayerLast(playr, tail());
}

}

// *************************************************************************
void addPlayerLast(Player playr)
{
addPlayerLast(playr, this);
}

// *************************************************************************
// recursive print-out of player data (id, family name, first name, goals)
void printList(PlayerList list)
{
if(head() == null){
}
else{
//System.out.println(head().toString());
printList(tail());
}
}

// *************************************************************************
// just call printList(param) to allow for recursion and to keep the interface clean
void printList()
{
printList(this);
}

// *************************************************************************
// recursive computation of length of list
int lengthList(PlayerList list)
{
if(firstPlayer.getNext() == null){
return 1;
}
else{
return 1+lengthList(tail());
}
}

// *************************************************************************
int lengthList()
{
return lengthList(this);
}

// *************************************************************************
// recursive computation of sum of ages of all players in the list
int sumAge(PlayerList list)
{
if(firstPlayer.getNext() == null){
return firstPlayer.getAge();
}
else{

return head().getAge() + sumAge(tail());

}
}

// *************************************************************************
// recursive computation of sum of games of all players in the list
int sumAge()
{
return sumAge(this);
}

// *************************************************************************
/**
* @param args
*/
public static void main(String[] args)
{

PlayerList test = new PlayerList();
Player ilkay = new Player(1, "Guendokan", "Ilkay", 23, "Stauchung");
test.addPlayer(ilkay);
Player mats = new Player(2, "Hummels", "Mats", 24, "Baenderriss");
test.addPlayer(mats);
Player neven = new Player(3, "Subotic", "Neven", 25, "Kreuzbandriss");
test.addPlayer(neven);
Player sven = new Player(4, "Bender", "Sven", 24, "Innenbandanriss");
test.addPlayer(sven);
Player nuri = new Player(5, "Sahin", "Nuri", 25, "Sprunggelenk");
test.addPlayer(nuri);

System.out.println(test.sumAge());
System.out.println(test.head().getFamilyName()); // testing

//players.printList();
//System.out.println("length of list: " + test.lengthList());
//System.out.println("average age: " + (double) players.sumAge()/players.lengthList() + "\n");

}
}



Basically all methods with tail() do not work, the others like addPlayer work.

And regarding that null player list ... that's what it was says in the description: must create a new list (which may be empty = null)


You're sure the issue isn't with your getNext() function?
Average means I'm better than half of you.
DeltaX
Profile Joined August 2011
United States287 Posts
December 18 2013 23:51 GMT
#8174
Might want to include your player class as well.

**This might not be totally correct, correct me if I am wrong**

Also one thing with linked lists is that you have to watch the pointers. With your tail method, you make a new list, but with the same objects. If you keep the first list around after calling tail, you could have two lists accessing the same player objects and cause hard to troubleshoot problems if you are not looking for it.


Also, you may want to change your classes so that the linked list class keeps track of next and implements those methods. As it is now, each player object needs to know about another player object and I would say that is the job of your list class.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
December 19 2013 00:03 GMT
#8175
On December 19 2013 03:16 Manit0u wrote:
Show nested quote +
On December 19 2013 03:05 scudst0rm wrote:
On December 19 2013 02:35 Manit0u wrote:
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...

+ Show Spoiler +

#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i]
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j]
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i];
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.


Your while loop condition doesn't make sense. while (number == order[i]) will only be true on the first iteration when both are 0. after that you update number to a random value but order[i] will still be 0.


I knew I messed something up with the control statements and placement of things That's what you get for having 2 minutes at the computer and having to do different stuff for hours inbetween.

Show nested quote +
On December 19 2013 03:04 Morfildur wrote:
On December 19 2013 02:35 Manit0u wrote:
Help me please. I'm having a huge brainfart right now...

I want to create a small int array with numbers from 1 to 5 in it, but the numbers need to be randomly placed inside the array each time. C doesn't have the shuffle() function so I have to go about it manually but I guess I've been thinking too much about it and can't get it to work...

+ Show Spoiler +


#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
int order[5] = { 0, 0, 0, 0, 0 };
int number = 0;

srand((unsigned int) time(0));

for (int i = 0; i < 5; i += 1)
{
while (number == order[i]
{
number = rand() % 6;

if (i >= 1)
{
for (int j = 0; j < 4; j += 1)
{
if (number == order[j]
{
number = rand() % 6;
}
}
}
}

order[i] = number;

number = 0;

printf("%d \n", order[i];
}

return 0;
}



It's in ANSI C but if you can give me example on how to go about it in other languages (C++/Java/C# etc.) I'll be able to understand it too.


Untested since i'm too lazy, but this is a very simple shuffle implementation:

int array[5] = { 1,2,3,4,5 };
for (int i = 0; i < 5; ++i)
{
int new_pos = rand() % 5;
int temp = array[i];
array[i] = array[new_pos];
array[new_pos] = temp;
}


Basically, for every element in the array, you pick a random index and exchange the current element with the element at that index.


Tried it like that:


#include <stdlib.h>
#include <time.h>
#include <stdio.h>

int main (void)
{
srand((unsigned int) time(0));

int arr[5] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr);

while (n > 1)
{
int s = rand() % n;
int tmp = arr[n];

n -= 1;
arr[s] = arr[n];
arr[n] = tmp;
}

for (int i = 0; i < 5; i += 1)
{
printf("%d, ", arr[i]);
}

return 0;
}


It compiles just fine but throws the "memory protection error" at me. Any ideas where I went wrong?

Edit: This works but not as intended (some of the elements get doubled).


srand((unsigned int) time(0));

int arr[5] = { 1, 2, 3, 4, 5 };

for (int i = 0; i < 5; i += 1)
{
int s = rand() % 5;
int tmp = arr[i];

arr[i] = arr[s];
arr[s] = tmp;

printf("%d\n", arr[i]);
}


Edit2: I'm dumb... Forget about it

Keep in mind that while in the first solution every permutation is equally likely (well, almost... 2^32 or 2^64 is not divisible by 5, but that's negligible...), the second algorithm (by Morfildur) is "incorrect" -- some permutations are less likely than others.
Maero
Profile Joined December 2007
349 Posts
December 19 2013 00:15 GMT
#8176
On December 19 2013 08:45 WolfintheSheep wrote:
Show nested quote +
On December 19 2013 08:17 Vilanoil wrote:
On December 19 2013 08:06 bangsholt wrote:
How is the rest of your linked list implemented, and how are you using it, because I don't see something that should give you a stack overflow there.

Also you should check for null, then make a new list, as you're otherwise making a list that consists of a null player - which probably is not what you want.


Thats the complete class:

+ Show Spoiler +

public class PlayerList
{
private Player firstPlayer;

// constructor for empty list
PlayerList()
{
firstPlayer = null;
}

// constructor to start list with first player
PlayerList(Player playr)
{
firstPlayer = playr;
}

// *************************************************************************
// setter for first element
void setHead(Player playr)
{
firstPlayer = playr;
}

// *************************************************************************
// getter for first element
Player head()
{
return firstPlayer;
}

// *************************************************************************
// get rest of list
// note: this operation must create a new list (which may be empty = null)
PlayerList tail()
{
PlayerList list = new PlayerList(head().getNext());
if(list.head() == null){
final PlayerList empty = new PlayerList();
return empty;
}
return list;

}

// *************************************************************************
// add each new Student at the beginning of the list
void addPlayer(Player playr)
{
playr.setNext(head());
setHead(playr);
}

// *************************************************************************
// add each new Student recursively at the end of the list
void addPlayerLast(Player playr, PlayerList list)
{
if(list.head().getNext() == null){
list.head().setNext(head().getNext());
}
else{
addPlayerLast(playr, tail());
}

}

// *************************************************************************
void addPlayerLast(Player playr)
{
addPlayerLast(playr, this);
}

// *************************************************************************
// recursive print-out of player data (id, family name, first name, goals)
void printList(PlayerList list)
{
if(head() == null){
}
else{
//System.out.println(head().toString());
printList(tail());
}
}

// *************************************************************************
// just call printList(param) to allow for recursion and to keep the interface clean
void printList()
{
printList(this);
}

// *************************************************************************
// recursive computation of length of list
int lengthList(PlayerList list)
{
if(firstPlayer.getNext() == null){
return 1;
}
else{
return 1+lengthList(tail());
}
}

// *************************************************************************
int lengthList()
{
return lengthList(this);
}

// *************************************************************************
// recursive computation of sum of ages of all players in the list
int sumAge(PlayerList list)
{
if(firstPlayer.getNext() == null){
return firstPlayer.getAge();
}
else{

return head().getAge() + sumAge(tail());

}
}

// *************************************************************************
// recursive computation of sum of games of all players in the list
int sumAge()
{
return sumAge(this);
}

// *************************************************************************
/**
* @param args
*/
public static void main(String[] args)
{

PlayerList test = new PlayerList();
Player ilkay = new Player(1, "Guendokan", "Ilkay", 23, "Stauchung");
test.addPlayer(ilkay);
Player mats = new Player(2, "Hummels", "Mats", 24, "Baenderriss");
test.addPlayer(mats);
Player neven = new Player(3, "Subotic", "Neven", 25, "Kreuzbandriss");
test.addPlayer(neven);
Player sven = new Player(4, "Bender", "Sven", 24, "Innenbandanriss");
test.addPlayer(sven);
Player nuri = new Player(5, "Sahin", "Nuri", 25, "Sprunggelenk");
test.addPlayer(nuri);

System.out.println(test.sumAge());
System.out.println(test.head().getFamilyName()); // testing

//players.printList();
//System.out.println("length of list: " + test.lengthList());
//System.out.println("average age: " + (double) players.sumAge()/players.lengthList() + "\n");

}
}



Basically all methods with tail() do not work, the others like addPlayer work.

And regarding that null player list ... that's what it was says in the description: must create a new list (which may be empty = null)


You're sure the issue isn't with your getNext() function?


This is the answer - are you by any chance using recursion in getNext(), for some reason? In any case, could we see it?
Vilanoil
Profile Blog Joined July 2010
Germany47 Posts
December 19 2013 00:23 GMT
#8177
Okay thank you for your help. Here is the Player.class:
+ Show Spoiler +


public class Player
{
private int id;
private String familyName;
private String firstName;
private int age;
private String injury;
private Player next;

Player(int id, String familyName, String firstName, int age, String injury, Player next)
{
this.id = id;
this.familyName = familyName;
this.firstName = firstName;
this.age = age;
this.injury = injury;
this.next = next;
}

Player(int id, String familyName, String firstName, int age, String injury)
{
this(id, familyName, firstName, age, injury, null);
}

int getId() {
return id;
}

void setId(int id) {
this.id = id;
}

String getFamilyName() {
return familyName;
}

void setFamilyName(String familyName) {
this.familyName = familyName;
}

String getFirstName() {
return firstName;
}

void setFirstName(String firstName) {
this.firstName = firstName;
}

int getAge() {
return age;
}

void setAge(int age) {
this.age = age;
}

String getInjury() {
return injury;
}

void setInjury(String injury) {
this.injury = injury;
}

Player getNext() {
return next;
}

void setNext(Player next) {
this.next = next;
}
}
Maero
Profile Joined December 2007
349 Posts
December 19 2013 01:45 GMT
#8178
Could you give the stack trace of the stack overflow?
Cyx.
Profile Joined November 2010
Canada806 Posts
Last Edited: 2013-12-19 02:41:11
December 19 2013 02:33 GMT
#8179
On December 19 2013 06:56 Vilanoil wrote:
Hello, i need some help with linked lists in java. It's a program i have to write for my course and i can't find my error.
I am not allowed to use the API class for lists.
I somehow have a problem with my tail function which has to return a new list with out the head.

+ Show Spoiler +

// get rest of list
// note: this operation must create a new list (which may be empty = null)
PlayerList tail()
{
PlayerList list = new PlayerList(head().getNext());
if(list.head() == null)
{
PlayerList empty = new PlayerList();
return empty;
}
return list;

}


my constructors for the list:
+ Show Spoiler +

// constructor for empty list
PlayerList()
{
firstPlayer = null;
}

// constructor to start list with first player
PlayerList(Player playr)
{
firstPlayer = playr;
}


and well .. head().getNext() returns the 2nd Player object.

With the code like this i always get an java.lang.StackOverflowError. So i think it means that when i call tail() in my recursive functions it doens'f find the end of the list. But i can't figure out why.
Help please

EDIT: reading on a tablet and didn't reread before I posted lol, ignore me

EDIT2: so after reading more carefully, how long is your linked list? Because the recursive addPlayerLast call basically creates a copy of the linked list for every student in it, taking the first student off every time, which could rapidly cause some things to go crazy since your Player class has a fair bit of data in it... although that's only really a problem if it's a pretty long linked list, it might be worth looking at since you are getting a stack overflow ^^
DeltaX
Profile Joined August 2011
United States287 Posts
December 19 2013 03:23 GMT
#8180
Your main return condition in sumAge is an infinite loop.

hint: which object is head() and tail() getting called on?
Prev 1 407 408 409 410 411 1032 Next
Please log in or register to reply.
Live Events Refresh
Epic.LAN
13:00
Epic.LAN 48 Group Stage
Liquipedia
WardiTV Qualifier
12:00
Summer Cup, Qualifier #2
WardiTV611
Liquipedia
CrankTV Team League
11:00
Crank Gathers S4: Group Stage
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft: Brood War
Calm 7187
Rain 2610
Sea 1765
GuemChi 1218
Jaedong 1113
Hyuk 697
Shuttle 658
EffOrt 410
Mini 386
BeSt 379
[ Show more ]
firebathero 342
Soma 254
Rush 228
Snow 226
Stork 190
ggaemo 147
Zeus 117
Hyun 103
Larva 102
ZerO 91
hero 53
Free 53
soO 44
scan(afreeca) 36
JYJ 33
Sharp 32
Terrorterran 27
Barracks 26
ToSsGirL 24
sorry 24
Hm[arnc] 20
Bale 17
Yoon 15
IntoTheRainbow 14
Sacsri 13
JulyZerg 11
Sexy 11
ajuk12(nOOB) 10
Icarus 10
Purpose 8
Rock 6
Dota 2
Gorgc8076
syndereN177
League of Legends
Doublelift2117
Counter-Strike
byalli470
Other Games
singsing1688
B2W.Neo776
hiko565
Lowko388
crisheroes371
DeMusliM225
XaKoH 176
OGKoka 164
Liquid`VortiX69
djWHEAT69
Trikslyr15
ZerO(Twitch)9
ToD1
Organizations
Other Games
gamesdonequick2438
BasetradeTV207
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 13 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• escodisco2445
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Jankos2161
• TFBlade588
Upcoming Events
Big Brain Bouts
2h 38m
SHIN vs Elazer
Percival vs Nicoract
Reynor vs Lambo
Replay Cast
10h 38m
RSL Revival
19h 38m
Clem vs Lambo
Scarlett vs Cure
CranKy Ducklings
20h 38m
Epic.LAN
23h 38m
IPSL
1d 2h
Dragon vs Hawk
RSL Revival
1d 19h
Classic vs Trap
herO vs SHIN
Sparkling Tuna Cup
1d 20h
OSC
1d 23h
IPSL
2 days
Bonyth vs Ret
[ Show More ]
WardiTV Weekly
2 days
Monday Night Weeklies
3 days
PiGosaur Cup
4 days
The PondCast
4 days
Replay Cast
5 days
CrankTV Team League
5 days
Replay Cast
6 days
CrankTV Team League
6 days
Liquipedia Results

Completed

Proleague 2026-07-13
HSC XXIX
Eternal Conflict S2 E2

Ongoing

IPSL Spring 2026
Acropolis #4
CSL 2026 Summer (S21)
KCM Race Survival 2026 Season 3
Escore Tournament S3: W3
RSL Revival: Season 6
CranK Gathers Season 4: BW vs SC2 Team League
SCTL 2026 Spring
Stake Ranked Episode 3
XSE Pro League 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026

Upcoming

ASL S22 SEASON OPEN Day 1
Escore Tournament S3: W4
ASL S22 SEASON OPEN Day 2
Escore Tournament S3: W5
CSLAN 4
Blizzard Classic Cup 2026
HSC XXX
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
Light Tournament 2026
Eternal Conflict S2 Finale
Eternal Conflict S2 E3
Logitech G Connect 2026
StarSeries Fall 2026
FISSURE Playground #5
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer 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 © 2026 TLnet. All Rights Reserved.