Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/string/add binary #1

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ Checked implementations are written in scala. If not, those are not converted to
- [array](src/main/scala/algorithms/array)
- [x] [CircularCounter](src/main/scala/algorithms/array/CircularCounter.scala)
- [x] [Flatten](src/main/scala/algorithms/array/Flatten.scala)
- [x] [Garage](src/main/scala/algorithms/array/Garage.scala)
- [x] [LongestNonRepeat](src/main/scala/algorithms/array/LongestNonRepeat.scala)
- [x] [MergeIntervals](src/main/scala/algorithms/array/MergeIntervals.scala)
- [x] [garage](src/main/scala/algorithms/array/Garage.scala)
- [longest_non_repeat](python/array/longest_non_repeat.py/)
- [merge_intervals](python/array/merge_intervals.py)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

master 브랜치에 업데이트된 부분이 되돌아가있네요. 수정부탁드려요

- [x] [MissingRanges](src/main/scala/algorithms/array/MissingRanges.scala)
- [plus_one](python/array/plus_one.py)
- [x] [plus_one](src/main/scala/algorithms/array/PlusOne.scala)
- [x] [RotateArray](src/main/scala/algorithms/array/RotateArray.scala)
- [summary_ranges](python/array/summary_ranges.py)
- [x] [ThreeSum](src/main/scala/algorithms/array/ThreeSum.scala)
Expand All @@ -39,9 +39,7 @@ Checked implementations are written in scala. If not, those are not converted to
- [shortest_distance_from_all_buildings](python/bfs/shortest_distance_from_all_buildings.py)
- [word_ladder](python/bfs/word_ladder.py)
- [bit](python/bit)
- [bytes_int_conversion](pytho/bit/bytes_int_conversion.py)
- [count_ones](python/bit/count_ones.py)
- [find_missing_number](python/bit/find_missing_number.py)
- [power_of_two](python/bit/power_of_two.py)
- [reverse_bits](python/bit/reverse_bits.py)
- [single_number2](python/bit/single_number2.py)
Expand Down Expand Up @@ -141,7 +139,7 @@ Checked implementations are written in scala. If not, those are not converted to
- [stack](python/stack/stack.py)
- [valid_parenthesis](python/stack/valid_parenthesis.py)
- [string](python/string)
- [add_binary](python/string/add_binary.py)
- [x] [add_binary](src/main/scala/algorithms/string/AddBinary.scala)
- [breaking_bad](python/string/breaking_bad.py)
- [decode_string](python/string/decode_string.py)
- [encode_decode](python/string/encode_decode.py)
Expand Down
38 changes: 0 additions & 38 deletions python/array/plus_one.py

This file was deleted.

112 changes: 76 additions & 36 deletions src/main/scala/algorithms/array/Garage.scala
Original file line number Diff line number Diff line change
@@ -1,51 +1,91 @@
package algorithms.array

import scala.collection.mutable

/**
* There is a parking lot with only one empty spot. Given the initial state
* of the parking lot and the final state. Each step we are only allowed to
* move a car
* out of its place and move it into the empty spot.
* The goal is to find out the least movement needed to rearrange
* the parking lot from the initial state to the final state.
*
* Say the initial state is an array:
*
* [1,2,3,0,4],
* where 1,2,3,4 are different cars, and 0 is the empty spot.
*
* And the final state is
*
* [0,3,2,1,4].
* We can swap 1 with 0 in the initial array to get [0,2,3,1,4] and so on.
* Each step swap with 0 only.
* # There is a parking lot with only one empty spot. Given the initial state
*# of the parking lot and the final state. Each step we are only allowed to
*# move a car
*# out of its place and move it into the empty spot.
*# The goal is to find out the least movement needed to rearrange
*# the parking lot from the initial state to the final state.
**
# Say the initial state is an array:
**
# [1,2,3,0,4],
*# where 1,2,3,4 are different cars, and 0 is the empty spot.
**
# And the final state is
**
# [0,3,2,1,4].
*# We can swap 1 with 0 in the initial array to get [0,2,3,1,4] and so on.
*# Each step swap with 0 only.
**
Example
*input : 1, 2, 3, 0, 4
*final : 0, 3, 2, 1, 4
**
answer : 4 steps
**
step 1 : 0, 2, 3, 1, 4
*step 2 : 2, 0, 3, 1, 4 // 없으면 0 제외한 가장 앞에 것과 swap
*step 3 : 2, 3, 0, 1, 3
*step 4 : 0, 3, 2, 1, 4
*site : https://discuss.leetcode.com/topic/67928/rearrange-parking-lot
*site : https://www.careercup.com/question?id=5687257423937536
*
* User: before30
* Date: 2017. 5. 9.
* Time: PM 8:49
*/
object Garage {

def apply(init: List[Int], fin: List[Int]): Int = {
if (init.size != fin.size) throw new IllegalArgumentException("Size of initial and final state is not equal")

var i = 0
var move = 0
var list = init.drop(0)

while (list != fin) {
val v = list.apply(i)
val f = fin.apply(i)
def swap(current: List[Int], emptyIdx: Int, targetIdx: Int): List[Int] = {
current.updated(emptyIdx, current(targetIdx)).updated(targetIdx, current(emptyIdx))
}

if (v != 0 && v != f) {
list = list.updated(list.indexOf(0), v).updated(i, 0)
move += 1
def isFinished(currentGarage: List[Int], finalGarage: List[Int]): Boolean = {
currentGarage == finalGarage
}

if (list.indexOf(v) != fin.indexOf(v)) {
list = list.updated(list.indexOf(v), list.apply(fin.indexOf(v))).updated(fin.indexOf(v), v)
move += 1
def calc(initGarage: scala.collection.mutable.MutableList[Int], desigredGarage: List[Int]): Int = {
var step = 0
for ( i <- 0 until initGarage.length ) {
if (initGarage(i) != desigredGarage(i)
&& desigredGarage(i) != 0) {
val indexOfZero = initGarage.indexOf(0)
if (i != indexOfZero) {
val temp = initGarage(i)
initGarage(i) = 0
initGarage(indexOfZero) = temp
step = step + 1
}
val indexOfTarget = initGarage.indexOf(desigredGarage(i))
initGarage(i) = initGarage(indexOfTarget)
initGarage(indexOfTarget) = 0
step = step + 1
}

i = (i + 1) % init.size
}

move
step
}

def getFirstDeprecntExceptZero(currentGarage: List[Int], finalGarage: List[Int]): Either[String, Int] = {

Left("nothing")
}

def main(args: Array[String]): Unit = {
// println(swap(List(1,2,3,4,0), 4, 0))
// println(isFinished(List(1, 2, 3, 4, 5), List(1, 2, 3, 4, 5)))
// println(isFinished(List(1,2,3,4,5), List(2,1,3,4,5)))

// println(calc(List(1,2,3,0), List(1,2,3,0)))
/*
input : 1, 2, 3, 0, 4
final : 0, 3, 2, 1, 4

*/
println(calc(mutable.MutableList(1, 2, 3, 0, 4), List(0, 3, 2, 1, 4)))
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

기존의 구현이 잘못된 것이 아니라면 굳이 빼지 않고 새로운 구현을 추가해나가는 형태로 하는것이 어떨까 합니다.

Garage object 내에 함수를 다르게 두거나 같은 파일 내에 구현에 따라 object 파일을 따로 두는 방식으로 변경해주실 수 있나요?

main 함수의 코드는 테스트 목적으로 두신 것이라면 test 코드로 옮겨주시는것은 어떨까요?

52 changes: 52 additions & 0 deletions src/main/scala/algorithms/array/PlusOne.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package algorithms.array

import scala.collection.immutable.Stream.Empty

/**
* User: before30
* Date: 2017. 5. 8.
* Time: AM 8:59
*
* Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
* You may assume the integer do not contain any leading zero, except the number 0 itself.
* The digits are stored such that the most significant digit is at the head of the list.
*
* Example
* f([1, 2, 3] : 123) = [1, 2, 4]: 124
* f([9, 9, 9] : 999) = [1, 0, 0, 0]: 1000
*/
object PlusOne {

def apply(digits: List[Int], digit: Int): List[Int] = {
plusDigit(digits, digit)
}

def apply(digits: List[Int]): List[Int] = {
plusOne(digits)
}

def plusOne(digits: List[Int]): List[Int] = {
plusDigit(digits, 1)
}

def plusDigit(digits: List[Int], digit: Int): List[Int] = {
val test = calc(digits.reverse, digit, Nil)
println(test)
test
}

def calc(digits: List[Int], carry: Int, acc: List[Int]): List[Int] = {
digits match {
case Nil if carry == 0 => acc
case Nil if carry > 0 => carry::acc
case _ => {
val temp = digits.head + carry
calc(digits.tail, temp/10, temp%10::acc)
}
}
}

def main(args: Array[String]): Unit = {
plusOne(List(1,2,3))
}
}
48 changes: 48 additions & 0 deletions src/main/scala/algorithms/string/AddBinary.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package algorithms.string

/**
* Created by before30 on 16/05/2017.
*/

/*
Given two binary strings,
return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".
*/

object AddBinary {

// "1111", "1" -> 10000

def add(list1: List[Int], list2: List[Int], carry: Int, acc: List[Int]): List[Int] = {
if (list1.isEmpty && list2.isEmpty && carry != 0) carry::acc
else if(list1.isEmpty && list2.isEmpty && carry == 0) acc
else {
val (h1, t1) = if (!list1.isEmpty) (list1.head, list1.tail) else (0, Nil)
val (h2, t2) = if (!list2.isEmpty) (list2.head, list2.tail) else (0, Nil)
val c1 = (h1 + h2 + carry) / 2
val v = (h1 + h2 + carry) % 2
add(t1, t2, c1, v :: acc)
}


}
def apply(a: String, b: String): String = {

add(a.toList.map(x => x - '0').reverse, b.toList.map(x => x - '0').reverse, 0, Nil).mkString("")
}

def main(args: Array[String]): Unit = {
println("10000 == " + AddBinary("1111", "1"))
println("0 == " + AddBinary("0", "0"))
println("10 == " + AddBinary("1", "1"))
println("10000000001 == " + AddBinary("10000000000", "1"))
println("10000 == " + AddBinary("1101", "11"))
println("10000 ==" + AddBinary("1", "1111"))
println("101 ==" + AddBinary("001", "100"))
}
}
26 changes: 13 additions & 13 deletions src/test/scala/algorithms/array/GarageTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,25 @@ package algorithms.array

import algorithms.UnitSpec


/**
* User: before30
* Date: 2017. 5. 9.
* Time: PM 11:19
*/
class GarageTest extends UnitSpec {

"Garage" when {

"size of initial and final state is equal" should {
"success" in {
assert(Garage(List(1, 2, 3, 0, 4), List(0, 3, 2, 1, 4)) == 4)
}
"Method Test" should {
"swap test" in {
assert(Garage.swap(List(1,2,3,4,0), 4, 0) == List(0,2,3,4,1))
}

"size of initial and final state is not equal" should {
"throw IllegalArgumentException" in {
intercept[IllegalArgumentException] {
Garage(List(1, 2, 3, 0, 4), List(0, 3, 2, 1))
}
}
"isFinished true" in {
assert(Garage.isFinished(List(1,2,3,4,5), List(1,2,3,4,5)) == true)
}

"isFinished false" in {
assert(Garage.isFinished(List(1,2,3,4,5), List(1,2,3,5,4)) == false)
}
}

}
20 changes: 20 additions & 0 deletions src/test/scala/algorithms/array/LongestSubstring.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package algorithms.array

/**
* User: before30
* Date: 2017. 5. 10.
* Time: PM 12:02
*
* Difficulty : Medium
* Given a string, find the length of the longest substring without repeating characters.
*
* Examples:
* Given "abcabcbb", the answer is "abc", which the length is 3.
* Given "bbbbb", the answer is "b", with the length of 1.
* Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*
* site : https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
*/
object LongestSubstring {

}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이부분은 구현이 빠져있네요

35 changes: 35 additions & 0 deletions src/test/scala/algorithms/array/PlusOneTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package algorithms.array

import algorithms.UnitSpec

/**
* User: before30
* Date: 2017. 5. 8.
* Time: AM 9:16
*/
class PlusOneTest extends UnitSpec {
"PlusOne" should {

"success1" in {
assert(PlusOne(List(1, 2, 3)) == List(1, 2, 4))
}

"success2" in {
assert(PlusOne(List(9, 9, 9)) == List(1, 0, 0, 0))
}

}

"PlusDigit" should {

"success1" in {
assert(PlusOne(List(1, 2, 3), 2) == List(1, 2, 5))
}

"success2" in {
assert(PlusOne(List(9, 9, 9), 2) == List(1, 0, 0, 1))
}

}

}
Loading