Bit-based universe simulationProject Euler #11 Largest product in a gridGoogle Code Jam Google String problem: a sequence resulting from bit flips and reversalsSaving the Universe - Code Jam 2008 Qualification problem ABit shifting in PythonPython - lookahead driver for a parsing chainA-Star Search with 3D UniverseBlackjack strategy simulationParallel processing simulationCounting lower vs non-lowercase tokens for tokenized text with several conditionsBirthday paradox simulation
Data normalization before or after train-test split?
Why do Klingons use cloaking devices?
In the Seventh Seal why does Death let the chess game happen?
Advice for making/keeping shredded chicken moist?
Convenience stores in India
Why do we need a bootloader separate than our application program in MCU's?
Who pays for increased security measures on flights to the US?
Milky way is orbiting around?
My players like to search everything. What do they find?
Could you sell yourself into slavery in the USA?
Did Snape really give Umbridge a fake Veritaserum potion that Harry later pretended to drink?
What units are kpts?
How to travel between two stationary worlds in the least amount of time? (time dilation)
Can a Time Lord survive with just one heart?
Can 4 Joy cons connect to the same Switch?
What is the name of the technique when an element is repeated at different scales?
Taking advantage when the HR forgets to communicate the rules
Did Stalin kill all Soviet officers involved in the Winter War?
Should I hide my travel history to the UK when I apply for an Australian visa?
How might boat designs change in order to allow them to be pulled by dragons?
How can one synthesise a conjugated alkyne chain?
Short SF story , future people who feed on sunlight try solid food
Interview Question - Card betting
How frequently do Russian people still refer to others by their patronymic (отчество)?
Bit-based universe simulation
Project Euler #11 Largest product in a gridGoogle Code Jam Google String problem: a sequence resulting from bit flips and reversalsSaving the Universe - Code Jam 2008 Qualification problem ABit shifting in PythonPython - lookahead driver for a parsing chainA-Star Search with 3D UniverseBlackjack strategy simulationParallel processing simulationCounting lower vs non-lowercase tokens for tokenized text with several conditionsBirthday paradox simulation
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.
To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.
My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.
import sys
def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0
def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state
def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False
def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)
num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")
What are some ways to improve the performance of my code?
python python-3.x programming-challenge python-2.x time-limit-exceeded
$endgroup$
add a comment |
$begingroup$
I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.
To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.
My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.
import sys
def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0
def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state
def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False
def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)
num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")
What are some ways to improve the performance of my code?
python python-3.x programming-challenge python-2.x time-limit-exceeded
$endgroup$
1
$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
Jun 25 at 21:00
add a comment |
$begingroup$
I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.
To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.
My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.
import sys
def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0
def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state
def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False
def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)
num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")
What are some ways to improve the performance of my code?
python python-3.x programming-challenge python-2.x time-limit-exceeded
$endgroup$
I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.
To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.
My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.
import sys
def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0
def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state
def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False
def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)
num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")
What are some ways to improve the performance of my code?
python python-3.x programming-challenge python-2.x time-limit-exceeded
python python-3.x programming-challenge python-2.x time-limit-exceeded
edited Jun 25 at 16:05
200_success
134k21 gold badges170 silver badges440 bronze badges
134k21 gold badges170 silver badges440 bronze badges
asked Jun 25 at 13:53
Gansaikhan ShurGansaikhan Shur
262 bronze badges
262 bronze badges
1
$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
Jun 25 at 21:00
add a comment |
1
$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
Jun 25 at 21:00
1
1
$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
Jun 25 at 21:00
$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
Jun 25 at 21:00
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!
Given two bits, the way to find out whether exactly one of them is 1 is to use the ^
operator (XOR).
You should be able to solve this challenge using bit-shifting (<<
and >>
operators) and ^
.
$endgroup$
add a comment |
$begingroup$
Testing for state repetition by if state in seen:
is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen
is a list, the search time is linear, making the total time complexity quadratic with the size of the period.
Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f222928%2fbit-based-universe-simulation%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!
Given two bits, the way to find out whether exactly one of them is 1 is to use the ^
operator (XOR).
You should be able to solve this challenge using bit-shifting (<<
and >>
operators) and ^
.
$endgroup$
add a comment |
$begingroup$
You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!
Given two bits, the way to find out whether exactly one of them is 1 is to use the ^
operator (XOR).
You should be able to solve this challenge using bit-shifting (<<
and >>
operators) and ^
.
$endgroup$
add a comment |
$begingroup$
You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!
Given two bits, the way to find out whether exactly one of them is 1 is to use the ^
operator (XOR).
You should be able to solve this challenge using bit-shifting (<<
and >>
operators) and ^
.
$endgroup$
You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!
Given two bits, the way to find out whether exactly one of them is 1 is to use the ^
operator (XOR).
You should be able to solve this challenge using bit-shifting (<<
and >>
operators) and ^
.
answered Jun 25 at 14:09
200_success200_success
134k21 gold badges170 silver badges440 bronze badges
134k21 gold badges170 silver badges440 bronze badges
add a comment |
add a comment |
$begingroup$
Testing for state repetition by if state in seen:
is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen
is a list, the search time is linear, making the total time complexity quadratic with the size of the period.
Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.
$endgroup$
add a comment |
$begingroup$
Testing for state repetition by if state in seen:
is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen
is a list, the search time is linear, making the total time complexity quadratic with the size of the period.
Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.
$endgroup$
add a comment |
$begingroup$
Testing for state repetition by if state in seen:
is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen
is a list, the search time is linear, making the total time complexity quadratic with the size of the period.
Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.
$endgroup$
Testing for state repetition by if state in seen:
is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen
is a list, the search time is linear, making the total time complexity quadratic with the size of the period.
Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.
answered Jun 25 at 15:27
vnpvnp
42.2k2 gold badges35 silver badges109 bronze badges
42.2k2 gold badges35 silver badges109 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f222928%2fbit-based-universe-simulation%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
Jun 25 at 21:00