I'm having trouble with my bubblesort. It's looping through one occurrence before ending. It takes in an input file with various names and ages and sorts them. So far it's printing out:
Stella is 11 years old.
Fred is 88 years old.
George is 22 years old.
Violet is 33 years old.
Rose is 77 years old.
Bob is 66 years old.
Lena is 55 years old.
Billy is 44 years old.
Nellie is 99 years old.
When i want it to print out:
Stella is 11 years old.
George is 22 years old.
Violet is 33 years old.
Billy is 44 years old.
Lena is 55 years old.
Bob is 66 years old.
Rose is 77 years old.
Fred is 88 years old.
Nellie is 99 years old.
Current code:
public void bubbleSort()
{
PersonNode previous = head;
PersonNode current = head.getNext();
boolean swap = true;
int j = 0;
while(swap)
{
swap = false;
while(previous != null)
{
if(previous.getNext() != null && previous.getAge() > previous.getNext().getAge())
{
String tempName = previous.getName();
Integer tempAge = previous.getAge();
current = previous.getNext();
previous.setName(current.getName());
previous.setAge(current.getAge());
current.setName(tempName);
current.setAge(tempAge);
swap = true;
}
previous = previous.getNext();
}
}
Any help is appreciated.
The code only "bubbles" one value, you will need to repeat the process from the start until no more swaps happen. It's a one-line change.
public void bubbleSort()
{
PersonNode previous = head;
PersonNode current = head.getNext();
boolean swap = true;
while(swap)
{
swap = false;
previous = head; /* restart */
while(previous != null)
{
if(previous.getNext() != null && previous.getAge() > previous.getNext().getAge())
{
String tempName = previous.getName();
Integer tempAge = previous.getAge();
current = previous.getNext();
previous.setName(current.getName());
previous.setAge(current.getAge());
current.setName(tempName);
current.setAge(tempAge);
swap = true;
}
previous = previous.getNext();
}
}
Related
I need to convert desimal number to 7 bit binary. Like the binary of 11(desimal) is 001011.
I did found a solution in starkoverflow but it doesn't work like i want
String dec2bin(int dec) {
var bin = '';
while (dec > 0) {
bin = (dec % 2 == 0 ? '0' : '1') + bin;
dec ~/= 2;
}
return bin;
}
it returns 1011, cuts all the zeros before 1011
How can i solve that?
Just use padLeft on the String before returning it to make sure it is a minimum length prefixed with zeros. Also, your dec2bin method can be simplified into just using toRadixString(2) on your input integer. So something like this:
String dec2bin(int dec) => dec.toRadixString(2).padLeft(6, '0');
void main() {
print(dec2bin(11)); // 001011
}
I'm having this problem for a while and I can't find a good way to resolve it. So I have a timestamp like this for example : local t = "00:00:0.031" and I'm trying to convert it into an array like this :
local ft = {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 31
}
This is pretty much the same no matter the language so if you have an idea on how to solve this but don't know Lua you can submit your answer anyway in any language. I tried solving it myself using regex and I'm quite sure it's possible this way...
Thank you for the interest to my question, have a good day (:
You could use string.match to extract the substrings in a first place. In a second time, you could use the function tonumber to convert it into numbers.
function ParseTimestampString (TimestampString)
local Hours, Minutes, Seconds, Milliseconds = string.match(TimestampString, "(%d+)%:(%d+)%:(%d+)%.(%d+)")
local Result
if Hours and Minutes and Seconds and Milliseconds then
Result = {
hours = tonumber(Hours),
minutes = tonumber(Minutes),
seconds = tonumber(Seconds),
milliseconds = tonumber(Milliseconds)
}
end
return Result
end
With the following code, you could get the results you want:
Result = ParseTimestampString("00:00:0.031")
print(Result.hours)
print(Result.minutes)
print(Result.seconds)
print(Result.milliseconds)
This should returns:
> Result = ParseTimestampString("00:00:0.031")
>
> print(Result.hours)
0
> print(Result.minutes)
0
> print(Result.seconds)
0
> print(Result.milliseconds)
31
Here is a not bad way using string.gmatch which is splitting by regex in Lua. Here the value is being split by either ":" or ".". Then there is a counter in place to match the index for the resulting table.
local t = "00:00:0.031"
local ft = {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0
}
local count = 1
for str in string.gmatch(t, "([^:|.]+)") do
ft[count] = tonumber(str)
count = count + 1
end
You can do a printing loop afterwards to check the results
for i = 1, 4 do
print(ft[i])
end
Output:
0
0
0
31
The main problem I have found with my solution is that it does not save the values under the keys listed but instead the numbers 1 2 3 4.
My Simplest Answer Will Be Just Split the given string by your regex, in This Case For HOUR:MIN:SEC.MS
first Split By (:) To Get HOUR MIN & SEC+MS, Then Split SEC+MS by (.) To separate Both seconds And milliseconds
Below is my answer in java
import java.util.*;
class timeX {
long hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 31;
//Convert Given Time String To Vars
timeX(String input) {
//Split Input By (:) For Hour, Minutes & Seconds+Miliseconds
String[] splitted=input.split(":");
this.hours=Long.parseLong(splitted[0]);
this.minutes=Long.parseLong(splitted[1]);
//Split Again For Seconds And Miliseconds By (.)
String[] splittedMandS=splitted[2].split("\\.");
this.seconds=Long.parseLong(splittedMandS[0]);
this.milliseconds=Long.parseLong(splittedMandS[1]);
}
}
public class Main
{
public static void main(String[] args)
{
timeX tmp = new timeX("30:20:2.031");
System.out.println("H: "+tmp.hours+" M: "+tmp.minutes+" S: "+tmp.seconds+" MS: "+tmp.milliseconds);
}
}
With Lua you can do...
The os.date() can be a format tool for seconds.
...but depends on Operating System.
This works on Linux but not (as i know so far) on MS-Windows.
print(os.date('%H:%M:%S',0-3600)) -- puts out: 00:00:00
print(os.date('%H:%M:%S',300-3600)) -- puts out: 00:05:00
Also it can output the date/time as a table.
> tshow=function(tab) for k,v in pairs(tab) do print(k,'=',v) end end
> tshow(os.date('*t'))
day = 4
year = 2021
month = 11
hour = 11
yday = 308
isdst = false
min = 23
wday = 5
sec = 51
...and unfortunally it has no milliseconds.
If the table output of os.date() is saved as a table...
> ttable=os.date('*t')
> os.time(ttable)
1636021672
> os.date(_,os.time(ttable))
Thu Nov 4 11:27:52 2021
> os.date('%H:%M:%S',os.time(ttable))
11:27:52
...then its key/value pairs can be used for: os.time()
Further code do nearly what you expect when in ttable key 1 is your time with milliseconds as a string...
local tshow=function(tab) for k,v in pairs(tab) do print(k,'=',v) end end
local ttable=os.date('*t') -- Create a time table
ttable[1]='0:0:0.31' -- Numbered keys in sequence are ignored by os.tim()
ttable[2]=ttable[1]:gsub('(%d+):(%d+):(%d+)[.](%d+)','return {year=ttable.year,month=ttable.month,day=ttable.day,hour=%1,min=%2,sec=%3,milliseconds=%4}')
-- That creates ttable[2] with the value:
--- return {year=ttable.year,month=ttable.month,day=ttable.day,hour=0,min=0,sec=0,milliseconds=31}
-- Lets convert it now to a table with...
ttable[2]=load(ttable[2])()
-- Using tshow() to look inside
tshow(ttable[2])
That will output...
milliseconds = 31
day = 4
year = 2021
hour = 0
month = 11
min = 0
sec = 0
And this will put it out formated with os.date()
print(os.date('%H:%M:%S.'..ttable[2].milliseconds,os.time(ttable[2])))
-- Output: 00:00:00.31
This question already has answers here:
How to round a Double to the nearest Int in swift?
(9 answers)
Closed 3 years ago.
I have a number like 73
how get max and min like 70 and 80.
or 173 I want to get 170 and 180 etc.
ceil(73/10) * 10 // round up 80
round(73/10) * 10 // round down 70
Playground:
EDIT: Here just provide an idea.
let value: Int = 75
func min(_ value: Int) {
value - value % 10
}
func max(_ value: Int) {
value + 10 - value % 10
}
min(value)
max(value)
This question already has answers here:
Is floating point math broken?
(31 answers)
Precision String Format Specifier In Swift
(31 answers)
Closed 6 years ago.
I have Double value is 7.92021 and I want to change it to 7.92 (Double type).
I was try 3 methods but all not worked!
Code 1:
let d1:Double = 7.92012
let d2 = Double(String(format: ".2f", d1))
// the result d2 = 7.92000000000002
Code 2:
let d1:Double = 7.92012
let value = NSDecimalNumber(double: d1)
value.decimalNumberByAdding(2)
let result = value.doubleValue
// the result = 7.92000000000002
Code 3:
let d1:Double = 7.92012
let d2 = round( d1 * 100 ) / 100
// d2 = 7.92000000000002
How I make the result value is 7.92 (double type)?
Lets say I have a normal page table:
Page Table (Page size = 4k)
Page #: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Page Frame #: 3 x 1 x 0 x 2 x 5 x 7 4 6 x x x
How can I convert an arbitrary logical address like 51996 into a physical memory address?
If I take log base 2 (4096), I get 12. I think this is how many bits I'm suppose to use for the offset of my address.
I'm just not sure. 51996 / 4096 = 12.69. So does this mean it lay on page#12 with a certain offset?
How do I then turn that into the physical address of "51996"?
To determine the page of a given memory address, take the first P bits (of the N bit) number.
P = lg2(numberOfPages)
In your example, P=lg2(16)=4
So the first 4 bits of a given memory address will tell us the page. That means the rest should be the offset from the start of that page.
Your example address, 51996, is 1100101100011100 in binary. I.e. [1100:101100011100].
1100 (12 in decimal) is the page number
101100011100 (2844 in decimal) is the offset
Now we need to find where page 12 is in memory.
Looking at your frame table, it appears that page 12 is resident in the 6th frame. In a system where all memory is pageable (i.e. no memory mapped IO) the 6th page frame will be at (entriesPerPage*frameNum)-1
In this case, 4000*6-1 = 23999 (The "-1" is needed since memory is 0-indexed.)
In this case, 4096*6-1 = 24575 (The "-1" is needed since memory is 0-indexed.)
Now all we have to do is add the offset and we have the physical memory address:
23999 + 2844=26843 = 0x68DB
24575 + 2844 = 27419 = 0x6B1B
Done!
Hope this (edit) was helpful XD
Edit:
Thanks to Jel for catching my mistake :)
Thanks to user8 for catching my other mistake! (frameNum instead of pageNum).
If I understand your question correctly (I probably don't), you want to know how to find the physical address from the virtual address using the page table structures. In that case, pretend you are the processor. Use the 10 most significant bits of the address to find the page table in the page directory (the top level page table). The next 10 bits are the index into the page table (the lower level page table). Use the address in that page table entry to find the physical page address. The last ten bits are the byte address into the page.
By the way, you would probably find a lot more people who would understand this type of question at an OS oriented site such as OSDev. I couldn't really go into much detail in this answer because I haven't done this type of stuff in years.
This is might help:
import java.util.Arrays;
import java.util.Scanner;
public class Run {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("////////// COMMANDS //////////");
System.out.println("Snapshot: S(enter)r, S(enter)m, S(enter)x, S(enter)p, S(enter)d, S(enter)c");
System.out.println("time: t");
System.out.println("Terminate: T#");
System.out.println("Kill: K#");
System.out.println("Start process: A");
System.out.println("Quit program: quit");
System.out.println("Deletes device: delete");
System.out.println ("//////////////////////////////");
OS myComputer;
int hdd, cdd, printer, cpu, mem, page;
hdd = cdd = printer = cpu = 20;
mem = 1;
page = 1;
System.out.println("");
System.out.println("|||| SYS GEN ||||");
System.out.println("");
mem = 0;
System.out.println("Number of Hard-Drives:");
while (hdd > 10) {
String inpt = input.next();
while (Asset.isInt(inpt) == false)
inpt = input.next();
hdd = Integer.parseInt(inpt);
if (hdd > 10)
System.out.println("Try something smaller (less than 10)");
}
System.out.println("Number of CD-Drives: ");
while (cdd > 10) {
String inpt = input.next();
while (Asset.isInt(inpt) == false)
inpt = input.next();
cdd = Integer.parseInt(inpt);
if (cdd > 10)
System.out.println("Try something smaller (less than 10)");
}
System.out.println("Number of Printers:");
while (printer > 10) {
String inpt = input.next();
while (Asset.isInt(inpt) == false)
inpt = input.next();
printer = Integer.parseInt(inpt);
if (printer > 10)
System.out.println("Try something smaller (less than 10)");
}
System.out.println("Amount of Memory:");
while (mem <= 0) {
String inpt = input.next();
if (Asset.isInt(inpt))
mem = Integer.parseInt(inpt);
if (mem<=0)
System.out.println("The memory size must be greater than zero.");
else
break;
}
Integer[] factors = Asset.factors(mem);
System.out.println("Enter a page size: "+Arrays.toString(factors));
while (true) {
String inpt = input.next();
while (Asset.isInt(inpt) == false)
inpt = input.next();
if (Asset.inArray(factors, Integer.parseInt(inpt))) {
page = Integer.parseInt(inpt);
break;
} else {
System.out.println("Page size must be one of these -> "+Arrays.toString(factors));
}
}
System.out.println("Number of CPUs (max10):");
while (cpu > 10) {
String inpt = input.next();
while (Asset.isInt(inpt) == false)
inpt = input.next();
cpu = Integer.parseInt(inpt);
if (cpu > 10)
System.out.println("Try something smaller (less than 10)");
}
myComputer = new OS(cpu, hdd, cdd, printer, mem, page);
myComputer.Running();
}
}
first step : 51996 / 4000 = 12 -> p , remain= 3996 -> d (offset).
now look at the table p(12) = 6
second step : (6*4000) + 3996 : 27996
the physical address is 27996.
The following page table is for a system with 16-bit virtual and physical addresses and with 4,096-byte pages. The reference bit is set to 1 when the page has been referenced. Periodically, a thread zeroes out all values of the reference bit. A dash for a page frame indicates the page is not in memory. The page-replacement algorithm is localized LRU, and all numbers are provided in decimal.
Page Page Frame Reference Bit
0 9 0
1 1 0
2 14 0
3 10 0
4 - 0
5 13 0
6 8 0
7 15 0
8 0 0
9 - 0
10 5 0
11 4 0
12 - 0
13 3 0
14 - 0
15 2 0
a. Convert the following virtual addresses (in hexadecimal) to the equivalent physical addresses (provide answers in hexadecimal AND decimal). Also set the reference bit for the appropriate entry in the page table. (3)
i. 0xBC2C
ii. 0x00ED
iii. 0xEA14
iv. 0x6901
v. 0x23A1
vi. 0xA999