• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 11:02
CET 17:02
KST 01:02
  • 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 Season 3 - Playoffs Preview0RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10
Community News
Weekly Cups (Nov 24-30): MaxPax, Clem, herO win2BGE Stara Zagora 2026 announced14[BSL21] Ro.16 Group Stage (C->B->A->D)4Weekly Cups (Nov 17-23): Solar, MaxPax, Clem win3RSL Season 3: RO16 results & RO8 bracket13
StarCraft 2
General
Weekly Cups (Nov 24-30): MaxPax, Clem, herO win SC2 Proleague Discontinued; SKT, KT, SGK, CJ disband BGE Stara Zagora 2026 announced Information Request Regarding Chinese Ladder SC: Evo Complete - Ranked Ladder OPEN ALPHA
Tourneys
$5,000+ WardiTV 2025 Championship Constellation Cup - Main Event - Stellar Fest RSL Revival: Season 3 Tenacious Turtle Tussle [Alpha Pro Series] Nice vs Cure
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 502 Negative Reinforcement Mutation # 501 Price of Progress Mutation # 500 Fright night Mutation # 499 Chilling Adaptation
Brood War
General
Which season is the best in ASL? FlaSh's Valkyrie Copium [ASL20] Ask the mapmakers — Drop your questions BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion
Tourneys
[Megathread] Daily Proleagues [BSL21] RO16 Group B - Sunday 21:00 CET [BSL21] RO16 Group C - Saturday 21:00 CET Small VOD Thread 2.0
Strategy
Game Theory for Starcraft How to stay on top of macro? Current Meta PvZ map balance
Other Games
General Games
Stormgate/Frost Giant Megathread Path of Exile Nintendo Switch Thread Should offensive tower rushing be viable in RTS games? The Perfect Game
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 TL Mafia Community Thread
Community
General
Things Aren’t Peaceful in Palestine US Politics Mega-thread Russo-Ukrainian War Thread The Big Programming Thread Artificial Intelligence Thread
Fan Clubs
White-Ra Fan Club
Media & Entertainment
[Manga] One Piece Movie Discussion! Anime Discussion Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Where to ask questions and add stream? The Automated Ban List
Blogs
James Bond movies ranking - pa…
Topin
Esports Earnings: Bigger Pri…
TrAiDoS
Thanks for the RSL
Hildegard
Saturation point
Uldridge
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1299 users

The Big Programming Thread - Page 183

Forum Index > General Forum
Post a Reply
Prev 1 181 182 183 184 185 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.
Deleted User 101379
Profile Blog Joined August 2010
4849 Posts
October 27 2012 18:23 GMT
#3641
On October 28 2012 03:20 Thorakh wrote:
+ Show Spoiler +
private static boolean containsDuplicates(int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] != 0)
{
for (int j=i+1; j<array.length; j++)
{
if (array[i] == array[j]
{
return true;
}
}
}
}

return false;
}


What on earth would cause this code to hang? I'm trying to check an array for duplicate integers, ignoring zeroes. Sometimes it hangs, sometimes it doesn't O_O


It shouldn't hang at any point but it will throw an exception when i == array.length - 1 if i read this correctly because then j == array.length => out of bounds.
Craton
Profile Blog Joined December 2009
United States17274 Posts
October 27 2012 18:24 GMT
#3642
On October 27 2012 18:04 supereddie wrote:
You should be able to figure out what is the bottleneck in your code. If there is no clear bottleneck and the CPU is not running at 100% capacity, it might be possible to use more than one thread to do the processing (maybe one thread per line, max of 10 threads). But perhaps this is not allowed when using Java stored procedures.

I have no way of monitoring CPU load.
twitch.tv/cratonz
Thorakh
Profile Joined April 2011
Netherlands1788 Posts
Last Edited: 2012-10-27 18:30:22
October 27 2012 18:25 GMT
#3643
On October 28 2012 03:23 Morfildur wrote:
Show nested quote +
On October 28 2012 03:20 Thorakh wrote:
+ Show Spoiler +
private static boolean containsDuplicates(int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] != 0)
{
for (int j=i+1; j<array.length; j++)
{
if (array[i] == array[j]
{
return true;
}
}
}
}

return false;
}


What on earth would cause this code to hang? I'm trying to check an array for duplicate integers, ignoring zeroes. Sometimes it hangs, sometimes it doesn't O_O


It shouldn't hang at any point but it will throw an exception when i == array.length - 1 if i read this correctly because then j == array.length => out of bounds.
It isn't doing that though, and I haven't caught exceptions anywhere in my code.

But now that you mention it, that certainly is weird, especially the fact that no exceptions are being thrown.

edit: no wait, it never throws an exception because the code that would cause array[i] == array[j] to be an array overflow never executes when j=i+1 is larger than the array length.
Craton
Profile Blog Joined December 2009
United States17274 Posts
Last Edited: 2012-10-27 18:28:18
October 27 2012 18:27 GMT
#3644
Add debugging statements and exception handlers and see where it hangs. From that you can figure out your next step.
twitch.tv/cratonz
LukeNukeEm
Profile Joined February 2012
31 Posts
October 27 2012 18:32 GMT
#3645
On October 28 2012 02:06 ArdentZeal wrote:
Hello there,

i could need some help in c++.
I have several classes (State1, State2, State3, ...) derived from the base class State.
They all have the same method, which is used sligthly differently depending on the State i am in.

So I wrote the method Automat::setCurrentState(State* _nextState); to set the States accordingly.

But if i try to call this method with one of the derived classes, i get a compiler error. Do i really have to overwrite Automat::setCurrentState(State* _nextState); with each of the 20 States or is there a simple solution i am missing?

Some additional info might be useful. What is the compiler error?
Just a wild guess: are you using private or protected inheritance?
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2012-10-27 18:39:30
October 27 2012 18:38 GMT
#3646
On October 27 2012 16:18 Craton wrote:Oracle is housed on a secure server and we simply call whatever output procedure to do its thing (it dumps it to the filesystem of said secure server). Data CANNOT leave secure servers. Even moving from one server to the next requires a secure, semi-automated queuing system to move any files.

Because of the complexity of the data and what we do with it, as well as how much is already designed around Oracle, it makes no sense to try and redo everything in an environment outside of Oracle.

If you want to answer my question, then do so. Stop fighting me on existing business processes.

All I wanted to know is if I could match or better the output speed of what I have now versus a Java procedure that accomplished the same task more cleanly. Trying to point at everything EXCEPT what I asked is extremely aggravating.
Ok then, that's really unfortunate. I'm sorry if you felt I was fighting on this point, but from an outside perspective it is extremely aggravating to have to optimize the I/O bound last tiny bit of a problem, instead of a giant juicy easily-optimizable pile in the middle.

Now that I know you're limited to a secure room, oh well :\ At least you don't have to do your programming in an isolated, soundproofed, 200lbs-door locked room with no internet. Could be worse than simply having the unfortunate constraint of orcale and a single machine.

On October 27 2012 16:18 Craton wrote:I wouldn't even rate this as Alpha currently, so a lot of things are run step by step to bring things in and then modify it. The actual processing time for reading things in and then modifying them is pretty low (much lower than the time to output).
So like last post, how much time does it take to just read the data you need out of orcale as fast as possible? (Don't even save, just read and drop - maybe do something uninteresting to make sure the compiler doesn't optimize out). Once you know how fast your I/O is, you know the lower bound on how fast you can get. Figure out what the timing on your existing operation is, is it an order of magnitude worse? If so, we have something to work on, if not, I'd just throw up my hands and move on to the next problem.

If it is an order of magnitude worse, can you step through with a profiler? There's java visual vm, and a number of open source tools. I'm not sure about attaching it to an oracle db stored procedure, but you should be able to replicate the behavior with a not-in-orcale plain old java program.

Or there is supposedly a stored procedure profiler, but I'm not sure you're going to be able to get cpu / stack trace timing out of it, which is what we're really after - that is, unless the first thing you see after loading up the profiler is massive thrashing.

http://docs.oracle.com/cd/B10501_01/appdev.920/a96624/12_tune.htm#45936

On October 28 2012 03:24 Craton wrote:
Show nested quote +
On October 27 2012 18:04 supereddie wrote:
You should be able to figure out what is the bottleneck in your code. If there is no clear bottleneck and the CPU is not running at 100% capacity, it might be possible to use more than one thread to do the processing (maybe one thread per line, max of 10 threads). But perhaps this is not allowed when using Java stored procedures.

I have no way of monitoring CPU load.

shit just saw this, even with a profiler? Even with a profiler on a normal java program outside of oracle?
Who after all is today speaking about the destruction of the Armenians?
Thorakh
Profile Joined April 2011
Netherlands1788 Posts
Last Edited: 2012-10-27 19:01:18
October 27 2012 18:50 GMT
#3647
Java

Alright, my problem is bigger than I thought.

The following recursive method attempts to solve a sudoku (note that it works if there are no duplicates present in the supplied grid):

+ Show Spoiler +
public static boolean hasSolution(int[] grid)
{
boolean solved = false;
int candidateCell;
int trialValue;

if (isFull(grid))
{
solved = true;
}
else
{
candidateCell = getEmptyCell(grid);
trialValue = 1;

while (!solved && trialValue <= 9)
{
if (isLegal(grid, candidateCell, trialValue))
{
setCell(grid, candidateCell, trialValue);

if (hasSolution(grid))
{
solved = true;
}
else
{
clearCell(grid, candidateCell);
}
}

trialValue++;
}
}

return solved;
}


isFull(), getEmptyCell() - get's the next empty cell (a cell containing a 0), setCell() and clearCell() - resets the cell back to 0 - speak for themselves. The problem appears to be in isLegal():

+ Show Spoiler +
private static boolean isLegal(int[] grid, int candidateCell, int trialValue)
{
//Check the row of candidateCell for duplicate numbers. If a duplicate is found, the solution is illegal.
//Calculate the row number of the candidate cell.
int rowNumber = candidateCell / 9;
//Store the values of the row corresponding to the calculated row number in a new array.
int[] row = new int[9];
for (int i=0; i<row.length; i++)
{
row[i] = grid[rowNumber * 9 + i];
}
//Insert the trial value at the correct position.
row[candidateCell % 9] = trialValue;
//Check the row for duplicates, ignoring duplicate 0's.
if (containsDuplicates(row))
{
return false;
}

return true;
}


with containsDuplicates() being the code I posted earlier. Note that isLegal() only checks for rows at the moment. I have code for columns and blocks as well but I first need to solve this. I tried some sample grids to check if the code works by doing:

+ Show Spoiler +
int[] grid = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0};
if (SudokuSolver.hasSolution(grid))
{
SudokuSolver.showGrid(grid);
}
else
{
System.out.println("No solution!");
}


Now, this sample grid works perfectly. It has no solution and prints "No solution!". Sample grids with multiple 1's on one of the first two rows work (they tell me there is no solution). However, sample grids with multiple 1's on the 3th, 4th, 5th, 6th, 7th, 8th or 9th row, like:

+ Show Spoiler +
int[] grid = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 1, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0};


will keep running forever for an inexplicable reason. What the hell is happening here? I'm completely stumped.
Frigo
Profile Joined August 2009
Hungary1023 Posts
October 27 2012 19:09 GMT
#3648
On October 28 2012 03:23 Morfildur wrote:
Show nested quote +
On October 28 2012 03:20 Thorakh wrote:
+ Show Spoiler +
private static boolean containsDuplicates(int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] != 0)
{
for (int j=i+1; j<array.length; j++)
{
if (array[i] == array[j]
{
return true;
}
}
}
}

return false;
}


What on earth would cause this code to hang? I'm trying to check an array for duplicate integers, ignoring zeroes. Sometimes it hangs, sometimes it doesn't O_O


It shouldn't hang at any point but it will throw an exception when i == array.length - 1 if i read this correctly because then j == array.length => out of bounds.


It seems to be right, the problem must be elsewhere in your code.


package frigo;

public class DuplicateFinder {

public static boolean containsDuplicates (int[] array) {
for( int i = 0; i < array.length; i++ ){
if( array[i] != 0 ){
for( int j = i + 1; j < array.length; j++ ){
if( array[i] == array[j] ){
return true;
}
}
}
}
return false;
}

}




package frigo;

import static frigo.DuplicateFinder.containsDuplicates;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class DuplicateFinderTest {

@Test
public void testEmptyArrayDoesNotContainDuplicates () {
int[] array = {};
assertThat(containsDuplicates(array), is(false));
}

@Test
public void testMultipleElementArrayContainsDuplicates () {
int[] array = {0, 1, 1, 3, 4};
assertThat(containsDuplicates(array), is(true));

}

@Test
public void testMultipleELementArrayDoesNotContainDuplicates () {
int[] array = {0, 1, 2, 3, 4};
assertThat(containsDuplicates(array), is(false));
}

@Test
public void testSingleElementArrayDoesNotContainDuplicates () {
int[] array = {1};
assertThat(containsDuplicates(array), is(false));
}

@Test
public void testZerosAreNotCountedAsDuplicates () {
int[] array = {0, 0};
assertThat(containsDuplicates(array), is(false));
}

}
http://www.fimfiction.net/user/Treasure_Chest
Fyodor
Profile Blog Joined September 2010
Canada971 Posts
Last Edited: 2012-10-27 19:20:26
October 27 2012 19:19 GMT
#3649
On October 28 2012 03:50 Thorakh wrote:
Java

Alright, my problem is bigger than I thought.

The following recursive method attempts to solve a sudoku (note that it works if there are no duplicates present in the supplied grid):

+ Show Spoiler +
public static boolean hasSolution(int[] grid)
{
boolean solved = false;
int candidateCell;
int trialValue;

if (isFull(grid))
{
solved = true;
}
else
{
candidateCell = getEmptyCell(grid);
trialValue = 1;

while (!solved && trialValue <= 9)
{
if (isLegal(grid, candidateCell, trialValue))
{
setCell(grid, candidateCell, trialValue);

if (hasSolution(grid))
{
solved = true;
}
else
{
clearCell(grid, candidateCell);
}
}

trialValue++;
}
}

return solved;
}


isFull(), getEmptyCell() - get's the next empty cell (a cell containing a 0), setCell() and clearCell() - resets the cell back to 0 - speak for themselves. The problem appears to be in isLegal():

+ Show Spoiler +
private static boolean isLegal(int[] grid, int candidateCell, int trialValue)
{
//Check the row of candidateCell for duplicate numbers. If a duplicate is found, the solution is illegal.
//Calculate the row number of the candidate cell.
int rowNumber = candidateCell / 9;
//Store the values of the row corresponding to the calculated row number in a new array.
int[] row = new int[9];
for (int i=0; i<row.length; i++)
{
row[i] = grid[rowNumber * 9 + i];
}
//Insert the trial value at the correct position.
row[candidateCell % 9] = trialValue;
//Check the row for duplicates, ignoring duplicate 0's.
if (containsDuplicates(row))
{
return false;
}

return true;
}


with containsDuplicates() being the code I posted earlier. Note that isLegal() only checks for rows at the moment. I have code for columns and blocks as well but I first need to solve this. I tried some sample grids to check if the code works by doing:

+ Show Spoiler +
int[] grid = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0};
if (SudokuSolver.hasSolution(grid))
{
SudokuSolver.showGrid(grid);
}
else
{
System.out.println("No solution!");
}


Now, this sample grid works perfectly. It has no solution and prints "No solution!". Sample grids with multiple 1's on one of the first two rows work (they tell me there is no solution). However, sample grids with multiple 1's on the 3th, 4th, 5th, 6th, 7th, 8th or 9th row, like:

+ Show Spoiler +
int[] grid = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 1, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0};


will keep running forever for an inexplicable reason. What the hell is happening here? I'm completely stumped.


Seems like you need a 2d array bro.

Your position tracking seems pretty hacky to me and prone to bugs.
llllllllllllllllllllllllllllllllllllllllllll
Thorakh
Profile Joined April 2011
Netherlands1788 Posts
Last Edited: 2012-10-27 20:40:11
October 27 2012 20:07 GMT
#3650
Hmm, I just rewrote my program and it seems to work perfectly now, instead of doing all kinds of position calculations I just check the entire grid for legality of a move every time:

+ Show Spoiler +
public class Sudoku
{
public static boolean hasSolution(int[] grid)
{
boolean solved = false;
int candidateCell;
int trialValue;

if (!isGridLegal(grid))
{
return false;
}
if (isFull(grid))
{
solved = true;
}
else
{
candidateCell = getEmptyCell(grid);
trialValue = 1;

while (!solved && trialValue <= 9)
{
setCell(grid, candidateCell, trialValue);

if (hasSolution(grid))
{
solved = true;
}
else
{
clearCell(grid, candidateCell);
}

trialValue++;
}
}

return solved;
}

public static void showGrid(int[] grid)
{
for (int i=0; i<grid.length; i++)
{
System.out.print(grid[i]+" ");
if ((i+1) % 3 == 0)
{
System.out.print(" ");
}
if ((i+1) % 27 == 0)
{
System.out.println();
}
if ((i+1) % 9 == 0)
{
System.out.println();
}
}
}

private static boolean isGridLegal(int[] grid)
{
return areRowsLegal(grid) && areColumnsLegal(grid) && areBlocksLegal(grid);
}

private static boolean areRowsLegal(int[] grid)
{
int row[] = new int[9];
for (int i=0; i<grid.length; i+=9)
{
for (int j=0; j<9; j++)
{
row[j] = grid[i + j];
}
if (containsDuplicates(row))
{
return false;
}
}

return true;
}

private static boolean areColumnsLegal(int[] grid)
{
int[] column = new int[9];
for (int i=0; i<9; i++)
{
for (int j=0; j<grid.length; j+=9)
{
column[j / 9] = grid[i + j];
}
if (containsDuplicates(column))
{
return false;
}
}

return true;
}

private static boolean areBlocksLegal(int[] grid)
{
int[][] blocks = new int[9][9];
blocks[0] = new int[] { 0, 1, 2, 9, 10, 11, 18, 19, 20};
blocks[1] = new int[] { 3, 4, 5, 12, 13, 14, 21, 22, 23};
blocks[2] = new int[] { 6, 7, 8, 15, 16, 17, 24, 25, 26};
blocks[3] = new int[] {27, 28, 29, 36, 37, 38, 45, 46, 47};
blocks[4] = new int[] {30, 31, 32, 39, 40, 41, 48, 49, 50};
blocks[5] = new int[] {33, 34, 35, 42, 43, 44, 51, 52, 53};
blocks[6] = new int[] {54, 55, 56, 63, 64, 65, 72, 73, 74};
blocks[7] = new int[] {57, 58, 59, 66, 67, 68, 75, 76, 77};
blocks[8] = new int[] {60, 61, 62, 69, 70, 71, 78, 79, 80};

for (int i=0; i<blocks.length; i++)
{
int block[] = new int[9];
for (int j=0; j<blocks[i].length; j++)
{
block[j] = grid[blocks[i][j]];
}
if (containsDuplicates(block))
{
return false;
}
}

return true;
}

private static boolean containsDuplicates(int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] != 0)
{
for (int j=i+1; j<array.length; j++)
{
if (array[i] == array[j])
{
return true;
}
}
}
}

return false;
}

private static void clearCell(int[] grid, int cell)
{
grid[cell] = 0;
}

private static void setCell(int[] grid, int cell, int value)
{
grid[cell] = value;
}

private static int getEmptyCell(int[] grid)
{
for (int i=0; i<grid.length; i++)
{
if (grid[i] == 0)
{
return i;
}
}

return -1;
}

private static boolean isFull(int[] grid)
{
for (int i=0; i<grid.length; i++)
{
if (grid[i] == 0)
{
return false;
}
}

return true;
}
}


edit: changed hasSolution() a bit because if the very last cell in the grid would be open, it would just insert a 1 and isFull() would return true and report the sudoku solved without checking if the 1 in the last cell actually solved it.
white_horse
Profile Joined July 2010
1019 Posts
Last Edited: 2012-10-28 16:54:36
October 28 2012 16:50 GMT
#3651
Can you guys help me? I need to write a simple program where I have to store a user-inputted number of primes into a vector. Generating the number of primes is easy but I don't know how to make it so that it only stores X number of vectors :/

Here is my code so far. It outputs nothing when I enter an input for NPrimes, like NPrimes = 10.


+ Show Spoiler +

cout << "Input the number of primes to find: ";
int NPrimes;
cin >> NPrimes;

vector<int> primes;

int k = 0;
for (int i = 2; i < 1000000; i++) //checking for all primes between 2 and 100000
{
bool isprime = true;
for (int j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
{
isprime = false;
}
}

if (isprime == true) // If i is a prime, it goes into the do-while loop and plugs in each i into the vector
{ // "primes" for "NPrimes" number of times.
do
{
primes.push_back(i);
k++;
}while (k < NPrimes);

}
}
Translator
Frigo
Profile Joined August 2009
Hungary1023 Posts
October 28 2012 17:59 GMT
#3652
On October 29 2012 01:50 white_horse wrote:

do
{
primes.push_back(i);
k++;
}while (k < NPrimes);

That's just plain silly.

http://www.fimfiction.net/user/Treasure_Chest
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
Last Edited: 2012-10-28 18:08:06
October 28 2012 18:03 GMT
#3653
On October 29 2012 01:50 white_horse wrote:
Can you guys help me? I need to write a simple program where I have to store a user-inputted number of primes into a vector. Generating the number of primes is easy but I don't know how to make it so that it only stores X number of vectors :/

Here is my code so far. It outputs nothing when I enter an input for NPrimes, like NPrimes = 10.


+ Show Spoiler +

cout << "Input the number of primes to find: ";
int NPrimes;
cin >> NPrimes;

vector<int> primes;

int k = 0;
for (int i = 2; i < 1000000; i++) //checking for all primes between 2 and 100000
{
bool isprime = true;
for (int j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
{
isprime = false;
}
}

if (isprime == true) // If i is a prime, it goes into the do-while loop and plugs in each i into the vector
{ // "primes" for "NPrimes" number of times.
do
{
primes.push_back(i);
k++;
}while (k < NPrimes);

}
}


Don't have time to figure out exactly why your code doesn't work, but it's quite bloated and I think I see a logic error in your do while. Try something simpler (I did not test this code), note that j * j < i is the same as i < sqrt( j ), except it's much faster due to avoiding the slow sqrt( ) function:

cout << "Input the max range to search: ";
int range;
cin >> range;

vector<int> primes;

for(int i = 0; i < range; ++i)
{
for(int j = 2; j * j < i; ++j)
{
if(i % j == 0)
{
primes.push_back( j );
}
}
}
Fyodor
Profile Blog Joined September 2010
Canada971 Posts
October 28 2012 18:17 GMT
#3654
On October 29 2012 02:59 Frigo wrote:


do
{
primes.push_back(i);
k++;
}while (k < NPrimes);

That's just plain silly.


Yeah this is broken.



Don't have time to figure out exactly why your code doesn't work, but it's quite bloated and I think I see a logic error in your do while. Try something simpler (I did not test this code), note that j * j < i is the same as i < sqrt( j ), except it's much faster due to avoiding the slow sqrt( ) function:

cout << "Input the max range to search: ";
int range;
cin >> range;

vector<int> primes;

for(int i = 0; i < range; ++i)
{
for(int j = 2; j * j < i; ++j)
{
if(i % j == 0)
{
primes.push_back( j );
}
}
}

You sure about (j * j < i) being the same?
llllllllllllllllllllllllllllllllllllllllllll
freelander
Profile Blog Joined December 2004
Hungary4707 Posts
Last Edited: 2012-10-28 19:46:25
October 28 2012 18:28 GMT
#3655
nvm
And all is illuminated.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
October 28 2012 18:28 GMT
#3656
On October 29 2012 03:17 Fyodor wrote:
You sure about (j * j < i) being the same?


Well, take a looky:
j < sqrt( i )
square each side
j^2 < i
therefor
j * j < i
Fyodor
Profile Blog Joined September 2010
Canada971 Posts
Last Edited: 2012-10-28 18:50:36
October 28 2012 18:35 GMT
#3657
On October 29 2012 03:28 CecilSunkure wrote:
Show nested quote +
On October 29 2012 03:17 Fyodor wrote:
You sure about (j * j < i) being the same?


Well, take a looky:
j < sqrt( i )
square each side
j^2 < i
therefor
j * j < i

Fascinating. You're good.

BTW, whitehorse, if you want to stop a loop after X passes or at a certain point... you need a break statement.

Like in your original code, you use:

if (k >= NPrimes)
{
break;
}

if you want the program to stop once it found the right amount of primes. Your while loop won't loop only once every pass, it'll loop like 20 times and push the same value over and over.
llllllllllllllllllllllllllllllllllllllllllll
white_horse
Profile Joined July 2010
1019 Posts
October 28 2012 22:08 GMT
#3658
we're not allowed to use breaks or continues I still don't understand how to store, say just 10 prime numbers in the vector.
Translator
Fyodor
Profile Blog Joined September 2010
Canada971 Posts
Last Edited: 2012-10-28 22:26:01
October 28 2012 22:22 GMT
#3659
On October 29 2012 07:08 white_horse wrote:
we're not allowed to use breaks or continues I still don't understand how to store, say just 10 prime numbers in the vector.

Well it will find all the primes unless you break out of the division test.

You could make the loop index break the loop condition on purpose maybe? It wouldn't be an explicit break statement but it would achieve the same thing.


cout << "Input the max range to search: ";
int range;
cin >> range;

vector<int> primes;

for(int i = 0; i < range; ++i)
{
for(int j = 2; j * j < i; ++j)
{
if(i % j == 0)
{
primes.push_back( j );
}
}
if (primes.size() >= 10) // breaks the loop after it finds 10 prime numbers.
{
i = range;
}
}


(only works if size() returns an int lol, not sure if it does)
llllllllllllllllllllllllllllllllllllllllllll
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
Last Edited: 2012-10-28 22:45:54
October 28 2012 22:40 GMT
#3660
On October 29 2012 07:22 Fyodor wrote:
Show nested quote +
On October 29 2012 07:08 white_horse wrote:
we're not allowed to use breaks or continues I still don't understand how to store, say just 10 prime numbers in the vector.

Well it will find all the primes unless you break out of the division test.

You could make the loop index break the loop condition on purpose maybe? It wouldn't be an explicit break statement but it would achieve the same thing.


cout << "Input the max range to search: ";
int range;
cin >> range;

vector<int> primes;

for(int i = 0; i < range; ++i)
{
for(int j = 2; j * j < i; ++j)
{
if(i % j == 0)
{
primes.push_back( j );
}
}
if (primes.size() >= 10) // breaks the loop after it finds 10 prime numbers.
{
i = range;
}
}


(only works if size() returns an int lol, not sure if it does)

This won't break out of the second loop properly and you'll end up a bunch of primes. white_horse you just need to make your loop end when the vector's size reaches something. Where can you do this? In the comparison of the for loop using &&.

cout << "Input the max range to search: ";
int range;
cin >> range;

vector<int> primes;
const unsigned SIZE = 10;

for(int i = 0; i < range && primes.size( ) != SIZE; ++i)
{
for(int j = 2; j * j < i && primes.size( ) != SIZE; ++j)
{
if(i % j == 0)
{
primes.push_back( j );
}
}
}


There are lots of ways to detect when you have reached ten. You can use primes.size( ), you can count with an int each time you use push back.

There are also lots of ways to end your nested for loop; you can use conditions like I did, you could place your for loops into a function and use return to break both loops (probably the best way), you can use the goto trick to break from nested for loops, you can place the push_back call in an if statement and only push back if the size is under the SIZE constant (doesn't break the loop but stops adding), etc.
Prev 1 181 182 183 184 185 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 59m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Lowko412
LamboSC2 343
gerald23 54
MindelVK 41
StarCraft: Brood War
Calm 5125
Shuttle 1115
Larva 717
Mini 522
firebathero 351
Rush 305
PianO 292
Light 279
Snow 215
Movie 158
[ Show more ]
hero 140
Sea.KH 63
Mong 43
JYJ38
soO 26
Terrorterran 26
JulyZerg 23
Sacsri 20
HiyA 15
yabsab 10
Dota 2
Gorgc5450
qojqva2885
Dendi1126
420jenkins287
BananaSlamJamma214
Counter-Strike
fl0m7309
zeus1175
markeloff117
Other Games
B2W.Neo1458
hiko682
Hui .319
DeMusliM296
KnowMe139
Liquid`VortiX138
RotterdaM130
FrodaN115
QueenE114
Mew2King104
ArmadaUGS57
oskar44
Trikslyr1
Organizations
StarCraft: Brood War
lovetv 9
Kim Chul Min (afreeca) 7
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 19 non-featured ]
StarCraft 2
• poizon28 11
• Reevou 2
• Kozan
• LaughNgamezSOOP
• sooper7s
• AfreecaTV YouTube
• intothetv
• Migwel
• IndyKCrew
StarCraft: Brood War
• FirePhoenix7
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• C_a_k_e 2033
• WagamamaTV657
• Noizen46
League of Legends
• Nemesis3438
• Jankos2152
• TFBlade887
Upcoming Events
StarCraft2.fi
59m
PiGosaur Monday
8h 59m
Wardi Open
19h 59m
StarCraft2.fi
1d
Replay Cast
1d 7h
The PondCast
1d 17h
Replay Cast
2 days
Korean StarCraft League
3 days
CranKy Ducklings
3 days
SC Evo League
3 days
[ Show More ]
BSL 21
4 days
Sziky vs OyAji
Gypsy vs eOnzErG
OSC
4 days
Solar vs Creator
ByuN vs Gerald
Percival vs Babymarine
Moja vs Krystianer
EnDerr vs ForJumy
sebesdes vs Nicoract
Sparkling Tuna Cup
4 days
BSL 21
5 days
Bonyth vs StRyKeR
Tarson vs Dandy
Replay Cast
5 days
Wardi Open
5 days
StarCraft2.fi
5 days
Replay Cast
6 days
StarCraft2.fi
6 days
Liquipedia Results

Completed

Proleague 2025-11-28
RSL Revival: Season 3
Light HT

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
YSL S2
BSL Season 21
CSCL: Masked Kings S3
Slon Tour Season 2
Acropolis #4 - TS3
META Madness #9
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
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2

Upcoming

BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
Bellum Gens Elite Stara Zagora 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
Kuram Kup
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
eXTREMESLAND 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.